mn create-app example.micronaut.micronautguide \
--features= \
--build=maven \
--lang=kotlin \
--test=junit
Table of Contents
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 Kotlin.
2. What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOME
configured appropriately
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.
-
Download and unzip the source
4. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
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.
package example.micronaut
import io.micronaut.core.order.Ordered
import io.micronaut.http.HttpRequest
import io.micronaut.http.annotation.Filter
import io.micronaut.http.annotation.RequestFilter
import io.micronaut.http.annotation.ServerFilter
import io.micronaut.http.filter.ServerFilterPhase
import io.micronaut.http.util.HttpHeadersUtil
import org.slf4j.Logger
import org.slf4j.LoggerFactory
@ServerFilter(Filter.MATCH_ALL_PATTERN) (1)
class LoggingHeadersFilter : Ordered {
@RequestFilter (2)
fun filterRequest(request: HttpRequest<*>) {
HttpHeadersUtil.trace(LOG, request.headers)
}
override fun getOrder() = ServerFilterPhase.FIRST.order() (3)
companion object {
private val LOG: Logger = LoggerFactory.getLogger(LoggingHeadersFilter::class.java)
}
}
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"}
.
package example.micronaut
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
@Controller (1)
class HelloController {
@Get (2)
fun index() = mapOf("message" to "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 ./mvnw mn: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:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>test</scope>
</dependency>
10.1. Write tests
Create a MemoryAppender
to ease testing.
package example.micronaut
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.AppenderBase
class MemoryAppender : AppenderBase<ILoggingEvent>() {
private val events = mutableListOf<ILoggingEvent>()
override fun append(e: ILoggingEvent) {
events.add(e)
}
fun getEvents() = events
}
Create a test that verifies the filter logs HTTP header. It masks sensitive HTTP headers.
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.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.Assertions.assertDoesNotThrow
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.slf4j.LoggerFactory
@MicronautTest (1)
class HelloControllerTest {
@Test
fun testHelloFilterLogging(@Client("/") httpClient: HttpClient) { (2)
val appender = MemoryAppender()
val l = LoggerFactory.getLogger(LoggingHeadersFilter::class.java) as Logger
l.addAppender(appender)
appender.start()
val client = httpClient.toBlocking()
assertDoesNotThrow<String> {
client.retrieve(
HttpRequest.GET<Any>("/")
.header(HttpHeaders.AUTHORIZATION, "Bearer x")
.header("foo", "bar")
)
}
assertTrue(appender.getEvents()
.stream()
.map { obj: ILoggingEvent -> obj.formattedMessage }
.anyMatch { it == "foo: bar" }
)
assertTrue(appender.getEvents()
.stream()
.map { obj: ILoggingEvent -> obj.formattedMessage }
.anyMatch { it == "Authorization: *MASKED*" }
)
assertTrue(appender.getEvents()
.stream()
.map { obj: ILoggingEvent -> obj.formattedMessage }
.noneMatch() { it == "Authorization: Bearer x" }
)
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:
./mvnw test
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…). |