Logging request headers using logbac

Hi Team ,

is their is way to log request headers using logback

I tried my patterns but non of them worked for me

can you please share the correct way to do it
This my current pattern i’m using but not worked for me

   <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5[%X{req.remoteHost} %X{req.requestURI} External IP=%X{req.xForwardedFor}] %-5level %-40logger{36} - %msg%n</pattern>
        </encoder>

Thanks

Hi,
One option for you is to setup logback-access feature:
http://logback.qos.ch/access.html

But if you want to output http header values with any business log message from the application, you would need to use the so-called MDC feature:
http://logback.qos.ch/manual/mdc.html

So you create an HTTP filter in a core and/or web module. This filter intercepts all requests and sets up MDC logging context:

public class RequestHeaderFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        MDC.put("remoteAddr", request.getRemoteAddr());
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.remove("remoteAddr");
        }
    }

    @Override
    public void destroy() {

    }
}

Register this filter in the web.xml file:

    <filter>
        <filter-name>rh_filter</filter-name>
        <filter-class>com.company.playground.web.RequestHeaderFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>rh_filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

And then use the new variable in the logback.xml pattern as %X{remoteAddr}.

2 Likes