Spring Boot: ImmutableLog
Integrate ImmutableLog into Spring Boot applications using OncePerRequestFilter for automatic capture of all HTTP requests, with AOP support to instrument service methods.
Installation
The filter uses only libraries included in the Spring Boot starter. For AOP, add the dependency below:
Maven
<!-- pom.xml -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>Gradle
// build.gradle
implementation 'com.fasterxml.jackson.core:jackson-databind'Jackson is already included in spring-boot-starter-web. For AOP, add spring-boot-starter-aop.
HTTP Filter (OncePerRequestFilter)
Create the class below in your project. Spring Boot detects the @Component and registers the filter automatically without any additional configuration.
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.*;
import java.util.regex.Pattern;
@Component
public class ImmutableLogFilter extends OncePerRequestFilter {
@Value("${immutablelog.api-key}")
private String apiKey;
@Value("${immutablelog.service-name:my-service}")
private String serviceName;
@Value("${immutablelog.env:production}")
private String env;
@Value("${immutablelog.url:https://api.immutablelog.com}")
private String apiUrl;
private final ObjectMapper mapper = new ObjectMapper();
private final HttpClient http = HttpClient.newHttpClient();
private static final Set<String> SKIP_PATHS = Set.of(
"/health", "/actuator/health", "/ping"
);
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return SKIP_PATHS.contains(request.getRequestURI());
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain
) throws ServletException, IOException {
var wrappedReq = new ContentCachingRequestWrapper(request);
var wrappedRes = new ContentCachingResponseWrapper(response);
long startMs = System.currentTimeMillis();
Throwable caught = null;
try {
chain.doFilter(wrappedReq, wrappedRes);
} catch (Exception ex) {
caught = ex;
throw ex;
} finally {
long latencyMs = System.currentTimeMillis() - startMs;
emit(wrappedReq, wrappedRes, latencyMs, caught);
wrappedRes.copyBodyToResponse();
}
}
private void emit(
ContentCachingRequestWrapper req,
ContentCachingResponseWrapper res,
long latencyMs,
Throwable ex
) {
try {
int status = res.getStatus();
String method = req.getMethod();
String path = req.getRequestURI();
String requestId = UUID.randomUUID().toString();
// Custom event name via request attribute
String customEvent = (String) req.getAttribute("imtbl.eventName");
String eventName = customEvent != null
? customEvent
: method.toLowerCase() + "." + path.replace("/", ".").replaceAll("^\.+", "");
String type = status >= 500 ? "error"
: status >= 400 ? "error"
: status >= 300 ? "info"
: "success";
// Bare IP (no port) or null; when null, client_ip is left out of payload and meta.
String clientIp = getClientIp(req);
Map<String, Object> payloadMap = new LinkedHashMap<>();
payloadMap.put("method", method);
payloadMap.put("path", path);
payloadMap.put("status", status);
payloadMap.put("latency_ms", latencyMs);
if (clientIp != null) payloadMap.put("client_ip", clientIp);
payloadMap.put("user_agent", req.getHeader("User-Agent"));
byte[] body = req.getContentAsByteArray();
if (body.length > 0) {
payloadMap.put("request_body_hash", sha256Hex(body));
}
if (ex != null) {
Map<String, Object> errMap = new LinkedHashMap<>();
errMap.put("type", ex.getClass().getName());
errMap.put("message", ex.getMessage());
errMap.put("retryable", !(ex instanceof IllegalArgumentException));
payloadMap.put("error", errMap);
}
// Trilha imutavel: atributo imtbl.trail -> header X-Imtbl-Trail.
String trail = sanitizeTrail((String) req.getAttribute("imtbl.trail"));
if (trail == null) trail = sanitizeTrail(req.getHeader("X-Imtbl-Trail"));
// Todos os valores de meta precisam ser strings (http_status inclusive).
Map<String, String> meta = new LinkedHashMap<>();
meta.put("type", type);
meta.put("event_name", eventName);
meta.put("service", serviceName);
meta.put("request_id", requestId);
// "environment" e o nome canonico; "env" e mantido por compatibilidade.
meta.put("env", env);
meta.put("environment", env);
meta.put("http_method", method);
meta.put("http_status", String.valueOf(status));
// Rota concreta; se o framework expuser o template (ex: /users/{id}), prefira-o.
meta.put("http_route", path);
meta.put("log_level", type.equals("error") ? "error" : "info");
if (trail != null) meta.put("immutable_trail", trail);
// client_ip no meta (o SIEM so promove client_ip a source.ip): IP puro, sem porta.
// So confie no X-Forwarded-For atras de proxy/ALB confiavel.
if (clientIp != null) meta.put("client_ip", clientIp);
if (ex != null) {
meta.put("error_type", ex.getClass().getName());
if (ex.getMessage() != null && !ex.getMessage().isBlank()) {
String m = ex.getMessage();
meta.put("error_message", m.length() > 500 ? m.substring(0, 500) : m);
}
}
Map<String, Object> body2 = Map.of(
"payload", mapper.writeValueAsString(payloadMap),
"meta", meta
);
String json = mapper.writeValueAsString(body2);
var builder = HttpRequest.newBuilder()
.uri(URI.create(apiUrl + "/v1/events"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + apiKey)
// Idempotency-Key e OBRIGATORIO (sem ele a API responde 400).
.header("Idempotency-Key", requestId)
.header("Request-Id", requestId)
.header("X-Client-TZ", "America/Sao_Paulo")
.header("X-Client-Offset-Minutes", "-180");
if (trail != null) builder.header("X-Imtbl-Trail", trail);
var httpReq = builder
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
// Fire and forget - never blocks the response
http.sendAsync(httpReq, HttpResponse.BodyHandlers.discarding());
} catch (Exception ignored) {
// Never let audit logging break the application
}
}
/**
* Client IP for client_ip: the first X-Forwarded-For entry, else X-Real-IP, else the IP of
* the connection (getRemoteAddr()), taking the first one that is a valid IP. Returns null
* when none is. X-Forwarded-For and X-Real-IP are only trustworthy behind a proxy/ALB that
* overwrites them: without one, any caller can forge them.
*/
private String getClientIp(HttpServletRequest req) {
String xff = req.getHeader("X-Forwarded-For");
if (xff != null) {
String ip = bareIp(xff.split(",")[0]);
if (ip != null) return ip;
}
String xri = bareIp(req.getHeader("X-Real-IP"));
if (xri != null) return xri;
return bareIp(req.getRemoteAddr());
}
private static final Pattern IPV4 = Pattern.compile(
"(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}");
private static final Pattern IPV6_CHARS = Pattern.compile("[0-9A-Fa-f:.]+");
/**
* Trims v, strips a port ("10.0.0.1:8080", "[2001:db8::1]:8080") or brackets, and returns
* the bare IP, or null if it is not one. Never resolves a host name: IPv4 is matched by
* pattern, and InetAddress only sees strings with ':' made of hex digits, which it parses
* as an IPv6 literal (or rejects) without DNS.
*/
static String bareIp(String v) {
if (v == null) return null;
v = v.trim();
if (v.startsWith("[")) {
int end = v.indexOf(']');
String rest = end < 0 ? null : v.substring(end + 1);
if (rest == null || !(rest.isEmpty() || rest.matches(":\\d+"))) return null;
v = v.substring(1, end);
} else if (v.indexOf(':') > 0 && v.indexOf(':') == v.lastIndexOf(':')) {
v = v.substring(0, v.indexOf(':'));
}
if (IPV4.matcher(v).matches()) return v;
if (v.indexOf(':') < 0 || !IPV6_CHARS.matcher(v).matches()) return null;
try {
InetAddress.getByName(v);
return v;
} catch (Exception e) {
return null;
}
}
// Normaliza o immutable_trail (trim, max 256, sem ':').
// O servidor responde 400 invalid_immutable_trail se a regra for violada.
private String sanitizeTrail(String v) {
if (v == null) return null;
v = v.trim();
if (v.isEmpty()) return null;
v = v.replace(":", "-");
if (v.length() > 256) v = v.substring(0, 256);
return v;
}
private String sha256Hex(byte[] data) {
try {
var digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(data);
StringBuilder sb = new StringBuilder();
for (byte b : hash) sb.append(String.format("%02x", b));
return sb.toString();
} catch (Exception e) {
return "hash-error";
}
}
}Configuration
Add the configuration variables to application.properties or application.yml:
application.properties
# application.properties
immutablelog.api-key=${IMTBL_API_KEY}
immutablelog.service-name=${IMTBL_SERVICE_NAME:my-service}
immutablelog.env=${IMTBL_ENV:production}
immutablelog.url=https://api.immutablelog.comapplication.yml
# application.yml
immutablelog:
api-key: ${IMTBL_API_KEY}
service-name: ${IMTBL_SERVICE_NAME:my-service}
env: ${IMTBL_ENV:production}
url: https://api.immutablelog.comHow it works
1. Request wrapping
The filter wraps request and response in ContentCachingWrapper to allow reading the body without consuming the original stream.
2. Chain passthrough
chain.doFilter() is called normally: the request flows to the controller unchanged. Exceptions are captured and re-thrown after recording.
3. Async emission in finally
In the finally block, the event is assembled and sent via HttpClient.sendAsync(). The HTTP client is non-blocking. The response was already sent to the user.
4. Body hash
The request body is hashed with SHA-256. Never the raw content (only the digest) is sent to ImmutableLog, preserving data privacy.
Custom event
Set a semantic event name via request attribute. The filter uses this value instead of the auto-generated name (method + path).
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/payments")
public class PaymentController {
@PostMapping
public ResponseEntity<?> create(HttpServletRequest request, @RequestBody PaymentDto dto) {
// Override the auto-generated event name
request.setAttribute("imtbl.eventName", "payment.created");
// ... process payment ...
return ResponseEntity.ok(result);
}
}Immutable trail (immutable_trail)
A trail groups related events into a single auditable timeline. Set the imtbl.trail request attribute, or propagate it across services with the X-Imtbl-Trail header. The value goes through sanitizeTrail before sending.
@PostMapping("/flows/{id}/run")
public ResponseEntity<?> runFlow(@PathVariable String id, HttpServletRequest req) {
req.setAttribute("imtbl.trail", "flow-" + id);
// ... business logic ...
return ResponseEntity.ok(Map.of("status", "ok"));
}The trail cannot be empty, exceed 256 characters, or contain ":", violations return 400 invalid_immutable_trail. sanitizeTrail fixes the value before sending.
Path exclusion
Override shouldNotFilter() to skip health checks and monitoring endpoints. The filter is not executed for these paths.
@Component
public class ImmutableLogFilter extends OncePerRequestFilter {
// Skip specific paths - health checks and actuator endpoints
private static final Set<String> SKIP_PATHS = Set.of(
"/health", "/actuator/health", "/actuator/info", "/ping"
);
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
String path = request.getRequestURI();
return SKIP_PATHS.stream().anyMatch(path::startsWith);
}
// ... rest of the filter
}HandlerInterceptor (alternative)
Use HandlerInterceptor when you need access to the handler (controller method) or annotations. Register in WebMvcConfigurer.
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.*;
/**
* Alternative: HandlerInterceptor gives access to the handler method.
* Use this when you need the controller method name or annotations.
* Register in WebMvcConfigurer.addInterceptors().
*/
@Component
public class ImmutableLogInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
req.setAttribute("imtbl.startedAt", System.currentTimeMillis());
return true;
}
@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse res,
Object handler, Exception ex) {
long startedAt = (long) req.getAttribute("imtbl.startedAt");
long latencyMs = System.currentTimeMillis() - startedAt;
// emit event with latencyMs, req, res, ex ...
}
}
// In your WebMvcConfigurer:
// registry.addInterceptor(immutableLogInterceptor).addPathPatterns("/**");AOP: @AuditEvent for service methods
With Spring AOP, instrument any service method without modifying the business logic. Add spring-boot-starter-aop and create the annotation + aspect below.
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
// 1. Define the annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AuditEvent {
String value() default "";
}
// 2. Implement the aspect
@Aspect
@Component
public class AuditEventAspect {
private final ImmutableLogClient client; // inject your HTTP client
public AuditEventAspect(ImmutableLogClient client) {
this.client = client;
}
@Around("@annotation(auditEvent)")
public Object audit(ProceedingJoinPoint pjp, AuditEvent auditEvent) throws Throwable {
long startMs = System.currentTimeMillis();
String eventName = auditEvent.value().isBlank()
? pjp.getSignature().getName()
: auditEvent.value();
try {
Object result = pjp.proceed();
long latencyMs = System.currentTimeMillis() - startMs;
client.emitAsync(eventName, "success", latencyMs, null);
return result;
} catch (Throwable ex) {
long latencyMs = System.currentTimeMillis() - startMs;
client.emitAsync(eventName, "error", latencyMs, ex);
throw ex;
}
}
}
// 3. Use in any Spring bean:
@Service
public class PaymentService {
@AuditEvent("payment.processed")
public Payment process(PaymentRequest req) {
// ... logic
}
}@AuditEvent works on any Spring bean (Service, Component, Repository). The aspect captures exceptions and always emits the event in the finally block, guaranteeing traceability even on errors.
This documentation reflects the current integration behavior. For questions or advanced integrations, contact the support team.
meta fields
Beyond the payload, the meta object carries the fields the SIEM uses to normalize (ECS) and enrich the event. All meta values are strings.
| Field in meta | What it does in the SIEM |
|---|---|
event_name | The event label (e.g. http.GET.auth-me-user, Payment error), the identifier shown in the listing. Becomes event.action and derives event.category (e.g. a name with login → authentication). |
client_ip | Becomes source.ip with maximum precedence and provenance client_asserted. It is the only meta field that becomes source.ip. It must be a plain IP, without a port. See the section below. |
immutable_trail | Becomes imtbl.immutable_trail, which groups related events for investigation (e.g. one order, one user). |
type | Event severity: error / warning / info / success. Colors the badge in the listing. (event_type is accepted as a synonym.) |
http_method, http_status, http_route, log_level, environment, error_type, error_message | Sent by the middlewares, always as a string (including http_status, e.g. "200"). error_type and error_message only exist when there is an error. |
service, env, request_id | Metadata: indexed and queryable in the dashboard (search/filters). |
client_ip: end-user IP
The problem it solves
Between the browser and the core there are proxies/ALB. The IP the core sees on the connection is the previous hop (the client's backend or an AWS proxy), not the user's. Without action, source.ip would be the proxy IP, useless for geo, threat and IP-based detection. (Real example: XFF arrived as 44.192.13.3 (AWS) while the user was 179.110.4.205.)
The solution
The client's backend is the only one that sees the browser's real IP, so it forwards that IP in meta.client_ip when calling POST /v1/events.
How the SIEM handles it
- Validates it is an IP (v4/v6). A non-IP value is ignored, without dropping the event. An IP with a port (e.g.
1.2.3.4:5678) is also silently discarded. - Writes to
source.ipwith maximum precedence (see order below). - Stamps
imtbl.source_ip_origin = "client_asserted"; the UI shows the “User IP” badge. - Feeds GeoIP, threat intel and IP-based detection rules.
client_ipX-Forwarded-For (1º hop)X-Real-IPconnection IPProvenance and trust
client_ip is asserted by the tenant: the client's backend claims the IP, and it can be forged by whoever controls that backend. However it stays contained within the tenant (it never crosses another tenant's boundary). A threat/geo hit on a client_asserted value is a claim, not an edge observation.
How to obtain the IP in your backend
Try the candidates in order: the first IP from X-Forwarded-For (closest to the user), then X-Real-IP (if your proxy sets it) and finally the connection IP. Each candidate goes through a function that strips the port (1.2.3.4:5678, [2001:db8::1]:8080) and the brackets and checks that it is a real IP, without any DNS lookup. An invalid value (garbage, localhost, an IPv6 zone such as fe80::1%eth0) is ignored and the next candidate is tried. Send a plain IP, without a port, and if no candidate is a valid IP omit the client_ip key (meta does not accept null, and never send “unknown”).
Only behind a trusted proxy: reading the first IP from X-Forwarded-For is only safe when a trusted proxy or ALB sits in front of the application and overwrites or appends the header. Without a proxy, the client controls the header and can forge the IP, and the SIEM will promote that value to source.ip.
The getClientIp (clientIP, get_client_ip) code of this page's middleware implements this rule, in the candidate order it shows.
Payload example
{
"payload": "{\"user\":\"bob\",\"action\":\"login\"}",
"meta": {
"event_name": "user.login",
"client_ip": "179.110.4.205",
"immutable_trail": "user-bob"
}
}PII note: client_ip is PII and gets sealed into the immutable block (permanent). Decide consciously between forensic evidence and “right to be forgotten” before sending it.
