Search code examples
javaloggingjbossundertow

How to log into a file in Undertow embedded server?


I have simple example, where I implement an access log handler. It does log to a console. How to configure the logger to log to a specified file?

package com.zetcode;

import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.accesslog.AccessLogHandler;
import io.undertow.server.handlers.accesslog.JBossLoggingAccessLogReceiver;
import io.undertow.util.Headers;

class MyHandler implements HttpHandler {

    @Override
    public void handleRequest(HttpServerExchange exchange) {

        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
        exchange.getResponseSender().send("Hello there");
    }
}

public class UndertowLogEx {

    public static void main(String[] args) {

        Undertow server = Undertow.builder()
                .addHttpListener(8080, "0.0.0.0")
                .setHandler(new AccessLogHandler(new MyHandler(), new JBossLoggingAccessLogReceiver(),
                        "combined", UndertowLogEx.class.getClassLoader()))
                .build();

        server.start();
    }
}

Solution

  • The JBossLoggingAccessLogReceiver logs access logs to the jboss-logging facade. The jboss-logging facade will log to whichever log manager you have configured. If you've got a console handler configured, it would log to the console.

    If you'd like to log to a file you could use the DefaultAccessLogReceiver.

    final ExecutorService executor = Executors.newSingleThreadExecutor();
    DefaultAccessLogReceiver.Builder builder = DefaultAccessLogReceiver.builder().setLogWriteExecutor(executor)
            .setOutputDirectory(Paths.get("/var/log/undertow"))
            .setLogBaseName("access-log.")
            .setLogNameSuffix("log")
            .setRotate(true);   
    
    Undertow server = Undertow.builder()
        .addHttpListener(8080, "0.0.0.0")
        .setHandler(new AccessLogHandler(new MyHandler(), builder.build(),
                "combined", UndertowUrlRewrite.class.getClassLoader()))
        .build();
    
    server.start();