Java Logging: show the source line number of the caller (not the logging helper method)

前端 未结 8 1357
太阳男子
太阳男子 2020-12-08 03:50

The numerous (sigh...) logging frameworks for Java all do a nice job of showing the line number of the source file name for the method that created the log message:

8条回答
  •  一生所求
    2020-12-08 04:28

    Adding details to KLE answer. (sorry, noob user, don't know better way than creating a separate answer )

    Instead of sticking the line number to the message, you can put it in the MDC context. See org.apache.log4j.MDC

    For example:

    StackTraceElement[] stackTraces = Thread.currentThread().getStackTrace();
    StackTraceElement stackTraceElement = ...;
    int l = stackTraceElement.getLineNumber();
    
    MDC.put("myLineNumber", l);
    

    That allows users to use mylineNumber in their log4j configuration file

    
        
    
    

    Note: that allows the user to control where and how the line number appears in the message. However, since getting the stacktrace is very costly, you still need to find a way to switch off the feature.

提交回复
热议问题