Ask Your Question
2

How can I modify the ExchangeAttribute to alter Undertow access logs?

asked 2023-01-05 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-05-19 07:00:00 +0000

pufferfish gravatar image

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}"
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-05 11:00:00 +0000

Seen: 15 times

Last updated: May 19 '21