1

While using MDC with log4j in a simple java(JDK-9) code, I am not getting any value for the MDC defined field. Below are My java code and log4j.properties file. Java code:

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
public class Logging {
public static void main(String[] args) {    
    Logger log = Logger.getLogger("Logging.class");  
    String a="BOB";
    try {
    log.info("Hello");
    MDC.put("userid",a);
    log.debug("Texting 1");
    } catch(Exception e) {
        log.error(e.getMessage());
    } finally {
        MDC.remove("userid");
    }    } }

log4j.properties:

log4j.rootLogger=DEBUG,consoleAppender
log4j.appender.consoleAppender=org.apache.log4j.ConsoleAppender
log4j.appender.consoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.consoleAppender.layout.ConversionPattern=%-4r [%t] %5p %c %x - %m - [%X{userid}]%n

Output:

0    [main]  INFO Logging.class  - Hello - []
4    [main] DEBUG Logging.class  - Texting 1 - []
Sarthak Sahu
  • 47
  • 11
  • This [what is the significance of log4j rootlogger property in log4j properties file](https://stackoverflow.com/questions/23869207/what-is-the-significance-of-log4j-rootlogger-property-in-log4j-properties-file) should help you out and add some insight as to what you're doing wrong (well not doing). Basically under `log4j.rootLogger=DEBUG,consoleAppender` you could add the line `log4j.logger.org.apache.log4j.MDC=TRACE` to get the most verbose logging. – JGlass Sep 28 '18 at 15:56
  • Well apparently in JAVA 9 the MDC.put() doesn't record anything. I tested it back with Java 8 and started getting the values. If anybody can disprove me, please do. – Sarthak Sahu Nov 06 '18 at 06:05

1 Answers1

1

In your code, just try to change the order and then try. I was getting same issue, I did change the order and tried,it is working for me. Let me share my code.

public class MyMDC {

public static void main(String[] args) {
    Logger log = Logger.getLogger(MyMDC.class);  
    String a="BOB";

    try {
        MDC.put("userid",a);
        log.info("Hello");
        log.debug("Texting 1");
        } 
    catch(Exception e) {
            log.error(e.getMessage());
        }
    finally {
            MDC.remove("userid");
        }    
}