How to add the Process id to a LOG4J log file?

后端 未结 3 701
时光说笑
时光说笑 2021-02-12 21:31

I currently have the below pattern layout in log4j. I want to add the Process id to the log file. How can I do it?

log4j.appender.A1.layout=org.apache.log4j.Pa         


        
3条回答
  •  名媛妹妹
    2021-02-12 21:53

    You should use MDC to do it

    In the config file :

    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy/MM/dd HH:mm:ss}  %-5p  (%c) %m%n %X{PID}
    

    %X{PID} is used to match the context value PID

    And then, in the code, before the logging begins :

    log4j 1.x

    RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
    String pid = rt.getName();
    MDC.put("PID", pid);
    

    log4j 2.x

    RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
    String pid = rt.getName();
    ThreadContext.put("PID", pid);
    

提交回复
热议问题