An extensible Java library for HTTP request and response logging
An extensible Java library for HTTP request and response logging
Logbook noun, /lɑɡ bʊk/: A book in which measurements from the ship's log are recorded, along with other salient details of the voyage.
Logbook is an extensible Java library to enable complete request and response logging for different client- and server-side technologies. It satisfies a special need by a) allowing web application developers to log any HTTP traffic that an application receives or sends b) in a way that makes it easy to persist and analyze it later. This can be useful for traditional log analysis, meeting audit requirements or investigating individual historic traffic issues.
Logbook is ready to use out of the box for most common setups. Even for uncommon applications and technologies, it should be simple to implement the necessary interfaces to connect a library/framework/etc. to it.
Contents:
Logbook's core functionality works without Jackson. JSON formatting (logbook-json) and JWT attribute extraction (JwtClaimsExtractor, etc.) are optional and support both Jackson 2 and Jackson 3 automatically.
How it works:
Logbook detects which Jackson version is available on the classpath and uses the appropriate implementation:
For Spring Boot 3.x:
spring-boot-starter-web or spring-boot-starter-jacksonFor Spring Boot 4.x:
spring-boot-starter-jackson<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.X.X</version>
</dependency>Manual configuration (if not using Spring Boot):
Add either Jackson 2 or Jackson 3 (or both):
Jackson 2:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.X.X</version>
</dependency>Jackson 3:
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>3.X.X</version>
</dependency>Add the following dependency to your project:
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-core</artifactId>
<version>${logbook.version}</version>
</dependency>Additional modules/artifacts of Logbook always share the same version number.
Alternatively, you can import our bill of materials...
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-bom</artifactId>
<version>${logbook.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>…The logbook logger must be configured to trace level in order to log the requests and responses. With Spring Boot (using Logback) this can be accomplished by adding the following line to your application.properties:
logging.level.org.zalando.logbook: TRACEAll integrations require an instance of Logbook which holds all configuration and wires all necessary parts together.
You can either create one using all the defaults:
Logbook logbook = Logbook.create();or create a customized version using the LogbookBuilder:
Logbook logbook = Logbook.builder()
.condition(new CustomCondition())
.queryFilter(new CustomQueryFilter())
.pathFilter(new CustomPathFilter())
.headerFilter(new CustomHeaderFilter())
.bodyFilter(new CustomBodyFilter())
.requestFilter(new CustomRequestFilter())
.responseFilter(new CustomResponseFilter())
.sink(new DefaultSink(
new CustomHttpLogFormatter(),
new CustomHttpLogWriter()
))
.build();Logbook used to have a very rigid strategy how to do request/response logging:
Some of those restrictions could be mitigated with custom HttpLogWriter
implementations, but they were never ideal.
Starting with version 2.0 Logbook now comes with a Strategy pattern
at its core. Make sure you read the documentation of the Strategy
interface to understand the implications.
Logbook comes with some built-in strategies:
Starting with version 3.4.0, Logbook is equipped with a feature called Attribute Extractor. Attributes are basically a list of key/value pairs that can be extracted from request and/or response, and logged with them. The idea was sprouted from issue 381, where a feature was requested to extract the subject claim from JWT tokens in the authorization header.
The AttributeExtractor interface has two extract methods: One that can extract attributes from the request only, and
one that has both request and response at its avail. The both return an instance of the HttpAttributes class, which is
basically a fancy Map<String, Object>. Notice that since the map values are of type Object, they should have a
proper toString() method in order for them to appear in the logs in a meaningful way. Alternatively, log formatters
can work around this by implementing their own serialization logic. For instance, the built-in log formatter
JsonHttpLogFormatter uses ObjectMapper to serialize the values.
Here is an example:
final class OriginExtractor implements AttributeExtractor {
@Override
public HttpAttributes extract(final HttpRequest request) {
return HttpAttributes.of("origin", request.getOrigin());
}
}Logbook must then be created by registering this attribute extractor:
final Logbook logbook = Logbook.builder()
.attributeExtractor(new OriginExtractor())
.build();This will result in request logs to include something like:
"attributes":{"origin":"LOCAL"}For more advanced examples, look at the JwtFirstMatchingClaimExtractor and JwtAllMatchingClaimsExtractor classes.
The former extracts the first claim matching a list of claim names from the request JWT token.
The latter extracts all claims matching a list of claim names from the request JWT token.
If you require to incorporate multiple AttributeExtractors, you can use the class CompositeAttributeExtractor:
final List<AttributeExtractor> extractors = List.of(
extractor1,
extractor2,
extractor3
);
final Logbook logbook = Logbook.builder()
.attributeExtractor(new CompositeAttributeExtractor(extractors))
.build();Logbook works in several different phases:
Each phase is represented by one or more interfaces that can be used for customization. Every phase has a sensible default.
Logging HTTP messages and including their bodies is a rather expensive task, so it makes a lot of sense to disable logging for certain requests. A common use case would be to ignore health check requests from a load balancer, or any request to management endpoints typically issued by developers.
Defining a condition is as easy as writing a special Predicate that decides whether a request (and its corresponding response) should be logged or not. Alternatively you can use and combine
predefined predicates:
Logbook logbook = Logbook.builder()
.condition(exclude(
requestTo("/health"),
requestTo("/admin/**"),
contentType("application/octet-stream"),
header("X-Secret", newHashSet("1", "true")::contains)))
.build();Exclusion patterns, e.g. /admin/**, are loosely following Ant's style of path patterns
without taking the the query string of the URL into consideration.
The goal of Filtering is to prevent the logging of certain sensitive parts of HTTP requests and responses. This usually includes the Authorization header, but could also apply to certain plaintext query or form parameters — e.g. password.
Logbook supports different types of filters:
| Type | Operates on | Applies to | Default |
|---|---|---|---|
QueryFilter |
Query string | request | access_token |
No open issues yet, or sync has not completed.