Search code examples
javalog4jlog4j2

Need to append params to each and every log before - in log4j in java


I need to append my variables to my logger for each and every log. Has to update the configuration log4J file to update the print statements for every log output. This information should be at the beginning of every log statement.

If you look at one of the log outputs : "2018-02-02 15:34:43 INFO TestClass:135 - Start time stamp is: 1517585580000 and HHmm is: 1533" I need to edit the part before the "-" i.e., 1533 param1 Param2 timestamp 2018-02-02 15:34:43 INFO TestClass:135 - - Start time stamp is: 1517585580000 and HHmm is: 1533. Note: the params vary from log to log i can pass them in through logger.info. Can anyone help me on this?


Solution

  • By using ThreadContext and pattern in log4j2.xml or log4j2.properties file in got expected output. Please find the below piece of code. log4j2.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration>
      <Appenders>
    
    <!--     Console Appender -->
        <Console name="Console" target="SYSTEM_OUT">
          <PatternLayout
            pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L %X{param1} %X{param2} %X{param3} - %m%n" />
        </Console>
    
      </Appenders>
      <Loggers>
        <Root level="all">
          <AppenderRef ref="Console" />
        </Root>
      </Loggers>
    </Configuration>
    

    or

    log4j2.properties

    # Root logger option
    log4j.rootLogger=INFO, file, stdout
    
    # Direct log messages to stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L %X{param1} %X{param2} %X{param3} - %m%n
    

    And

    In JAVA file

    package com.test;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.apache.logging.log4j.ThreadContext;
    
    public class Test {
        public static void ThreadContextLoggerCreation(long param1, String param2, String param3) {
            ThreadContext.push(UUID.randomUUID().toString()); // Add the fishtag;
            ThreadContext.put("param1", param1);
            ThreadContext.put("param2", param2);
            ThreadContext.put("param3", param3);
            ThreadContext.pop();
        }
    
        public static void ThreadContextLoggerClear() {
            ThreadContext.clearAll();
        }
        public static void main(String args[]) {
            Logger logger = LogManager.getLogger(Test.class);
            LogUtil.ThreadContextLoggerCreation(logger, currentTime, customerId, agentLocation, streamId, streamVariant, levelOfDetail);
            logger.info("Current Time of execution(HHmm) is: {}", BatchTimeUtil.convertTimestampToReadableDate(currentTime));
        }
    }