Configure MDC with SLF4j Logback file in java

This article is all about how you configure MDC logs with SLF4J and logback.

1. Maven POM dependencies: Please add maven dependencies as given below.

       <!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
</dependency>

2. Configure logback.xml file

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">

<property name="DEV_HOME" value="c:/logs" />
    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <resetJUL>true</resetJUL>
    </contextListener>

    
    <appender name="FILE-THREAD" class="ch.qos.logback.classic.sift.SiftingAppender">
        <discriminator>
<key>logFileName</key>
<defaultValue>head0</defaultValue>
 </discriminator>
 <sift>
<appender name="FILE-${logFileName}"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${DEV_HOME}/mdc.log</file>

<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%thread] %level %logger{35} - %msg%n
</Pattern>
</encoder>

<rollingPolicy
class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>${DEV_HOME}/mdc.%i.log.zip
</FileNamePattern>
<MinIndex>1</MinIndex>
<MaxIndex>10</MaxIndex>
</rollingPolicy>

<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
 </sift>
</appender>


<appender name="FILE_APPENDER" class="ch.qos.logback.core.FileAppender">
<file>${DEV_HOME}/mdc.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>
%X{clientName}, [%thread], %-5level %logger{36} - %msg%n
</Pattern>
</encoder>
</appender>

    
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
</Pattern>
</layout>
</appender>

<appender name="FILE-ERROR"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${DEV_HOME}/error.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} - %msg%n
</Pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${DEV_HOME}/archived/error.%d{yyyy-MM-dd}.%i.log
                        </fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>

</appender>

<!-- Send logs to both console and file audit -->
   <!--  here com.example is my root package -->
<logger name="com.example" level="INFO" additivity="false">

<appender-ref ref="FILE-THREAD" />
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE_APPENDER" />
</logger>

<root level="ERROR">
<appender-ref ref="FILE-ERROR" />
</root>


</configuration>


3. Use logging in java file

package com.example.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.slf4j.MDC;

@WebFilter( filterName = "mdcFilter", urlPatterns = { "/*" } )
public class MDCFilter implements Filter {

@Override
public void destroy() {

}

@Override
public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain )
throws IOException, ServletException {

// Get the parameter value.
final String parameter = request.getParameter( "clientName" );

// Put it in the MDC map.
MDC.put( "clientName", parameter );

try {
chain.doFilter( request, response );
} finally {
// When the control returns to the filter, clean it.
MDC.remove( "clientName" );
}
}

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

}

}

 4. You can also use slf4j logger

package com.example.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

.....
.....

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;


@Controller
public class UserController {

private static Logger logger=LoggerFactory.getLogger(UserController.class.getName());


@RequestMapping(value = "/rest/registerUser", method = RequestMethod.POST)
    public  @ResponseBody UserDTO registerUser(@RequestParam("name") String name, 
    @RequestParam("password") String password, @RequestParam("email") String email,
    @RequestParam("contactNumber") String contactNumber) {    


try {
logger.info("Registering user : name :"+name);
                        //TODO
} catch (Exception e) {

                           logger.error("Failed to register : Exception :"+e.getMessage());
   e.printStackTrace();
}
        
        return user;
    }
}

Popular posts from this blog

Can not connect to git using ssh (Permissions 0644 for '/root/.ssh/id_rsa' are too open.

Upload file on Google cloud storage using Java servlet on google app engine

Android: where to run keytool command in android