1

Creating an appender programmatically in java with log4j2.xml need to add MDC key variable with PatternLayout of Log4j2 , can any one look into below code and tell how to add mdc variable whose value will be replaced brfore the looger.info call

PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config)
            .withPattern("%d{HH:mm:ss.SSS} %level %msg%n").build();


final Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true",
              "false", "false", "4000", layout, null, "false", null, config);
   appender.start();
   addAppender(appender);
   LoggerConfig loggerConfig = LoggerConfig.createLogger("false", "info", "org.apache.logging.log4j",
              "true", refs, null, config, null );
   loggerConfig.addAppender(appender, null, null);
   addLogger("com", loggerConfig);

Now I need that whenever my log statements are printed they also print some value telling their state.

How can I add MDC key while creating above pattern layout ?

current behaviour of ==> logger.info(" Here we are "); is printing " Here we are "

My expectation is => statement should come with MDC key .

Rama Sharma
  • 96
  • 11

1 Answers1

0

Your pattern should contain something like %X{someKey} .

Then in your code, you would set the value, e.g :

MDC.put("someKey", someValue);
Arnaud
  • 17,229
  • 3
  • 31
  • 44