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

前端 未结 8 1355
太阳男子
太阳男子 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:44

    For Log4j2 the answer is provided completely by the use of logger wrappers as described in the Log4j2 manual under Example Usage of a Generated Logger Wrapper. One can simply generate (using the org.apache.logging.log4j.core.tools.Generate$ExtendedLogger tools illustrated there) a logger wrapper with a single STUB level, and then adapt that to create custom logging methods mimicking the use of the logIfEnabled(FQCN, LEVEL, Marker, message, Throwable) - possibly ignoring the STUB level and using the regular ones - then if desired, deleting or commenting out the STUB level and its methods). For this purpose the FormattedMessage can be helpful.

    The source line, while expensive, can then be easily shown as part of the full location information by using the %l location conversion pattern element in the PatternLayout given in the configuration, or more specifically using the %L line number and/or the %M method conversion.

    Now with complete example at: Java Logging: Log4j Version2.x: show the method of an end-client caller (not an intermediate logging helper method)

    0 讨论(0)
  • 2020-12-08 04:49

    Alternative answer.

    It is possible to ask log4j to exclude the helper class by using the method

    Category.log(String callerFQCN, Priority level, Object message, Throwable t)

    and specifying the helper class as 'callerFQCN'.

    For example here is a class using a helper:

    public class TheClass {
        public static void main(String...strings) {
            LoggingHelper.log("Message using full log method in logging helper.");
            LoggingHelper.logNotWorking("Message using class info method");
    }}
    

    and the code of the helper:

    public class LoggingHelper {
    private static Logger LOG = Logger.getLogger(LoggingHelper.class);
    
    public static void log(String message) {
        LOG.log(LoggingHelper.class.getCanonicalName(), Level.INFO, message, null);
    }
    
    public static void logNotWorking(String message) {
        LOG.info(message);
    } }
    

    The first method will output your expected result.

    Line(TheClass.main(TheClass.java:4)) Message using full log method in logging helper.
    Line(LoggingHelper.logNotWorking(LoggingHelper.java:12)) Message using class info method
    

    When using this method, Log4j will work as usual, avoiding calculating the stack trace if it is not required.

    0 讨论(0)
提交回复
热议问题