To modify ExchangeAttribute in Undertow access logs, you can follow the below steps:
Create a custom ExchangeAttribute implementation that generates the desired log output. For example, to log the user-agent header, you can create a class named UserAgentAttribute that extends ExchangeAttribute and overrides the readAttribute() method to return the user-agent value.
Add the custom ExchangeAttribute implementation to the Undertow request/response exchange.
Configure Undertow to use the custom ExchangeAttribute implementation in the access log format string.
For example, the following code adds UserAgentAttribute to the exchange and logs the user-agent header in the access log:
Undertow server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(
Handlers.path().addPrefixPath("/hello", exchange -> {
exchange.addExchangeCompleteListener(event -> {
exchange.putAttachment(UserAgentAttribute.ATTACHMENT_KEY, new UserAgentAttribute());
});
exchange.getResponseSender().send("Hello World!");
}))
.setHandler(accessLogHandler(
Handlers.path().addPrefixPath("/hello", exchange -> {
exchange.addExchangeCompleteListener(event -> {
exchange.putAttachment(UserAgentAttribute.ATTACHMENT_KEY, new UserAgentAttribute());
});
exchange.getResponseSender().send("Hello World!");
}),
new UserAgentAttribute()),
new AccessLogReceiver() {
@Override
public void logMessage(String message) {
System.out.println(message);
}
})
.build();
server.start();
And the access log format string with UserAgentAttribute:
%d{dd/MMM/yyyy:HH:mm:ss Z} [%s] %h %a "%r" %b "%{i,Referer}" "%{i,User-Agent,Unknown}"
Asked: 2023-01-05 11:00:00 +0000
Seen: 15 times
Last updated: May 19 '21