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

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=groovy \
    --test=spock
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/groovy/example/micronaut/LoggingHeadersFilter.groovy
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.headers)
    }

    @Override
    int getOrder() { (3)
        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/groovy/example/micronaut/HelloController.groovy
package example.micronaut

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

@Controller (1)
class HelloController {

    @Get (2)
    Map<String, Object> index() {
        [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/groovy/example/micronaut/MemoryAppender.groovy
package example.micronaut

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

class MemoryAppender extends AppenderBase<ILoggingEvent> {
    List<ILoggingEvent> events = new ArrayList<>()

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

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

src/test/groovy/example/micronaut/HelloControllerSpec.groovy
package example.micronaut

import ch.qos.logback.classic.Logger
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.spock.annotation.MicronautTest

import jakarta.inject.Inject
import org.slf4j.LoggerFactory
import spock.lang.Shared
import spock.lang.Specification

@MicronautTest (1)
class HelloControllerSpec extends Specification {

    @Shared
    @Client("/")
    @Inject
    HttpClient httpClient (2)

    void "invoking hello controller logs headers"() {
        given:
        MemoryAppender appender = new MemoryAppender()
        Logger l = (Logger) LoggerFactory.getLogger(LoggingHeadersFilter.class)
        l.addAppender(appender)
        appender.start()
        BlockingHttpClient client = httpClient.toBlocking()

        when:
        client.retrieve(HttpRequest.GET("/")
                .header(HttpHeaders.AUTHORIZATION, "Bearer x")
                .header("foo", "bar"))

        then:
        noExceptionThrown()
        appender.events.formattedMessage.any { it == "foo: bar" }
        appender.events.formattedMessage.every { it != "Authorization: Bearer x" }
        appender.events.formattedMessage.any { it == "Authorization: *MASKED*" }

        cleanup:
        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…​).