Log incoming HTTP Request headers with a Server Filter

Learn to log every HTTP Request header with a @ServerFilter and a method annotated with @FilterRequest.

Authors: Sergio del Amo

Micronaut Version: 4.6.3

1. Getting Started

In this guide, we will create a Micronaut application written in Java.

2. What you will need

To complete this guide, you will need the following:

3. Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

4. Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features= \
    --build=gradle \
    --lang=java \
    --test=junit
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add null features.

If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

5. Logback

Configure Logback to log the package example.micronaut with TRACE level.

<configuration>
    ...
    <logger name="example.micronaut" level="TRACE"/>
</configuration>

6. ServerFilter

Create a filter which logs the non-sensitive HTTP Request headers.

src/main/java/example/micronaut/LoggingHeadersFilter.java
package example.micronaut;

import io.micronaut.core.order.Ordered;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.annotation.RequestFilter;
import io.micronaut.http.annotation.ServerFilter;
import io.micronaut.http.filter.ServerFilterPhase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.micronaut.http.util.HttpHeadersUtil;
import static io.micronaut.http.annotation.Filter.MATCH_ALL_PATTERN;

@ServerFilter(MATCH_ALL_PATTERN) (1)
class LoggingHeadersFilter implements Ordered {

    private static final Logger LOG = LoggerFactory.getLogger(LoggingHeadersFilter.class);

    @RequestFilter (2)
    void filterRequest(HttpRequest<?> request) {
        HttpHeadersUtil.trace(LOG, request.getHeaders());
    }

    @Override
    public int getOrder() { (3)
        return ServerFilterPhase.FIRST.order();
    }
}
1 @ServerFilter marks a bean as a filter for the HTTP Server. The annotation value Filter.MATCH_ALL_PATTERN means the filter matches all requests.
2 A filter method annotated with @RequestFilter runs before the request is processed. A filter method must be declared in a bean annotated with @ServerFilter or @ClientFilter.
3 Filters can be ordered by implementing Ordered in the filter class.

7. Controller

Create a controller which responds a JSON object: {"message":"Hello World"}.

src/main/java/example/micronaut/HelloController.java
package example.micronaut;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

import java.util.Collections;
import java.util.Map;

@Controller (1)
public class HelloController {

    @Get (2)
    public Map<String, Object> index() {
        return Collections.singletonMap("message", "Hello World"); (3)
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /.
2 The @Get annotation maps the method to an HTTP GET request.
3 The Micronaut framework will automatically convert it to JSON before sending it.

8. Running the Application

To run the application, use the ./gradlew run command, which starts the application on port 8080.

curl localhost:8080 -H "X-Request-Id: 1234"

You will see in the logs:

... TRACE e.micronaut.LoggingHeadersFilter - Host: localhost:8080
... TRACE e.micronaut.LoggingHeadersFilter - User-Agent: curl/8.4.0
... TRACE e.micronaut.LoggingHeadersFilter - Accept: */*
... TRACE e.micronaut.LoggingHeadersFilter - X-Request-Id: 1234

9. Tests

10. Logback Dependency in test scope

In addition to the runtime classpath, add the logback-classic dependency to the test classpath:

build.gradle
testImplementation("ch.qos.logback:logback-classic")

10.1. Write tests

Create a MemoryAppender to ease testing.

src/test/java/example/micronaut/MemoryAppender.java
package example.micronaut;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;

import java.util.ArrayList;
import java.util.List;

public class MemoryAppender extends AppenderBase<ILoggingEvent> {

    private final List<ILoggingEvent> events = new ArrayList<>();

    @Override
    protected void append(ILoggingEvent e) {
        events.add(e);
    }

    public List<ILoggingEvent> getEvents() {
        return events;
    }
}

Create a test that verifies the filter logs HTTP header. It masks sensitive HTTP headers.

src/test/java/example/micronaut/HelloControllerTest.java
package example.micronaut;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertTrue;

@MicronautTest (1)
class HelloControllerTest {

    @Test
    void testHelloFilterLogging(@Client("/") HttpClient httpClient) { (2)
        MemoryAppender appender = new MemoryAppender();
        Logger l = (Logger) LoggerFactory.getLogger(LoggingHeadersFilter.class);
        l.addAppender(appender);
        appender.start();
        BlockingHttpClient client = httpClient.toBlocking();
        assertDoesNotThrow(() -> client.retrieve(HttpRequest.GET("/")
                .header(HttpHeaders.AUTHORIZATION, "Bearer x")
                .header("foo", "bar")));
        assertTrue(appender.getEvents()
                .stream()
                .map(ILoggingEvent::getFormattedMessage)
                .anyMatch(it -> it.equals("foo: bar")));
        assertTrue(appender.getEvents()
                .stream()
                .map(ILoggingEvent::getFormattedMessage)
                .noneMatch(it -> it.equals("Authorization: Bearer x")));
        assertTrue(appender.getEvents()
                .stream()
                .map(ILoggingEvent::getFormattedMessage)
                .anyMatch(it -> it.equals("Authorization: *MASKED*")));

        appender.stop();
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the HttpClient bean and point it to the embedded server.

11. Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

12. Next steps

Explore more features with Micronaut Guides.

Learn more about Filter Methods.

13. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

14. License

All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…​).