MDC in SLF4J and LOG4J




package tutorials.interviewbubble.SLF4J_LOG4J;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class App {
    private static Logger logger = LoggerFactory.getLogger(App.class);
    public static void main(String[] args) {
        MDCInterface();
    }
    static void process() {
        logger.info("Processing 1");
        logger.info("Processing 2");
        logger.info("Processing 3");
    }
    static void MDCInterface() {
        MDC.put("user", "Mohan");
        process();
        MDC.remove("user");
        process();
        MDC.put("user", "Karan");
        process();
        MDC.clear();
    }
}



xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
         <RollingFile name="fileLogger" fileName="logfiles/app-info.log" filePattern="logfiles/app-info-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
        
          <File name="markerfileLogger" fileName="logfiles/marker-info.log" >
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n</pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy  />
            </Policies>
            <Filters>
                <MarkerFilter marker="CONFIDENTIAL" onMatch="ACCEPT" onMismatch="DENY"/>
            </Filters>
        </File>
               
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout
                pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg - username=%X{user} %n" />
        </Console>
    </Appenders>
    <Loggers>
    
        <Root level="trace" additivity="false">
            <AppenderRef ref="console" />
            <appender-ref ref="fileLogger" level="debug" />
            <appender-ref ref="markerfileLogger"/>         
        </Root>
    </Loggers>

</Configuration>

Comments