而不是日志记录助手方法

而不是日志记录助手方法

本文介绍了Java日志记录:显示调用者的源行号(而不是日志记录助手方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java的众多(叹息......)日志框架都可以很好地显示创建日志消息的方法的源文件名的行号:

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:

log.info("hey");

 [INFO] [Foo:413] hey

但如果有介于两者之间的辅助方法,实际调用者将是辅助方法,而且信息量不大。

But if have a helper method in between, the actual caller will be the helper method, and that is not too informative.

log_info("hey");

[INFO] [LoggingSupport:123] hey

有没有办法在计算要打印的源位置时告诉日志系统从callstack中删除一个帧?

Is there a way to tell the logging system to remove one frame from the callstack when figuring out the source location to print?

我认为这是特定于实现的;我需要的是Log4J通过Commons Logging,但我很想知道其他选项。

I suppose that this is implementation specific; what I need is Log4J via Commons Logging, but I am interested to hear about other options.

推荐答案

替代答案。

可以通过使用方法让log4j排除帮助程序类

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)

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

并将助手类指定为'callerFQCN'。

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");
}}

以及帮助者的代码:

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

使用此方法时,Log4j将照常工作,如果不需要,则避免计算堆栈跟踪。

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

这篇关于Java日志记录:显示调用者的源行号(而不是日志记录助手方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 03:01