Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To modify ExchangeAttribute in Undertow access logs, you can follow the below steps:

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

  2. Add the custom ExchangeAttribute implementation to the Undertow request/response exchange.

  3. 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}"