Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

logbook

> 后端框架
Open source

An extensible Java library for HTTP request and response logging

2.1K stars0 likes0 views
WebsiteGitHub

About

An extensible Java library for HTTP request and response logging

Logbook: 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:

  • Features
  • Dependencies
    • Jackson Version Support
  • Installation
  • Usage
    • Strategy
    • Attribute Extractor
    • Phases
    • Servlet
    • HTTP Client
    • HTTP Client 5
    • JAX-RS 3.x (aka Jakarta RESTful Web Services)
    • JDK HTTP Server
    • Netty
    • OkHttp v2.x
    • OkHttp v3.x
    • Ktor
    • Spring
    • Spring Boot Starter
    • logstash-logback-encoder
  • Known Issues
  • Getting Help with Logbook
  • Getting Involved/Contributing
  • Alternatives
  • Credits and References

Features

  • Logging: of HTTP requests and responses, including the body; partial logging (no body) for unauthorized requests
  • Customization: of logging format, logging destination, and conditions that request to log
  • Support: for Servlet containers, Apache's HTTP client, Square's OkHttp, and (via its elegant API) other frameworks
  • Optional obfuscation of sensitive data
  • Spring Boot Auto Configuration
  • Scalyr compatible
  • Sensible defaults

Dependencies

  • Java 17 or higher (required - Spring 7 / Spring Boot 4 and JAX-RS 3.x)
  • Any build tool using Maven Central, or direct download
  • Servlet Container (optional)
  • Apache HTTP Client 4.x or 5.x (optional)
  • JAX-RS 3.x (aka Jakarta RESTful Web Services) Client and Server (optional)
  • Netty 4.x (optional)
  • OkHttp 2.x or 3.x (optional)
  • Spring 7.x (optional)
  • Spring Boot 4.x (optional)
  • Ktor (optional)
  • logstash-logback-encoder 5.x (optional)
  • Jackson 2.x or 3.x (optional, required for JSON formatting)

Jackson Version Support

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:

  • If Jackson 2 is available, Logbook uses Jackson 2 implementations (formatters, JWT extractors, and JSON compacting)
  • If Jackson 3 is available, Logbook uses Jackson 3 implementations (formatters, JWT extractors, and JSON compacting)
  • If both are available, Jackson 3 is preferred
  • If neither is available, JSON formatting is disabled but core logging still works

For Spring Boot 3.x:

  • Jackson 2 is provided by default via spring-boot-starter-web or spring-boot-starter-jackson
  • JSON formatting works out of the box with no additional configuration

For Spring Boot 4.x:

  • Jackson 3 is provided by default via spring-boot-starter-jackson
  • JSON formatting works out of the box with Jackson 3
  • If you want to use Jackson 2 instead, add it explicitly:
    xml
    <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:

xml
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.X.X</version>
</dependency>

Jackson 3:

xml
<dependency>
    <groupId>tools.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>3.X.X</version>
</dependency>

Installation

Add the following dependency to your project:

xml
<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...

xml
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.zalando</groupId>
      <artifactId>logbook-bom</artifactId>
      <version>${logbook.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
... which allows you to omit versions:
…

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: TRACE

Usage

All 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:

java
Logbook logbook = Logbook.create();

or create a customized version using the LogbookBuilder:

java
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();

Strategy

Logbook used to have a very rigid strategy how to do request/response logging:

  • Requests/responses are logged separately
  • Requests/responses are logged soon as possible
  • Requests/responses are logged as a pair or not logged at all
    (i.e. no partial logging of traffic)

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:

  • BodyOnlyIfStatusAtLeastStrategy
  • StatusAtLeastStrategy
  • WithoutBodyStrategy

Attribute Extractor

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:

java
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:

java
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:

java
final List<AttributeExtractor> extractors = List.of(
    extractor1,
    extractor2,
    extractor3
);

final Logbook logbook = Logbook.builder()
        .attributeExtractor(new CompositeAttributeExtractor(extractors))
        .build();

Phases

Logbook works in several different phases:

  1. Conditional,
  2. Filtering,
  3. Formatting and
  4. Writing

Each phase is represented by one or more interfaces that can be used for customization. Every phase has a sensible default.

Conditional

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:

java
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.

Filtering

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

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Javaclient-sidehttp-logsjavalogbook

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架