显示调用者的源代码行号

显示调用者的源代码行号

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

问题描述

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

log.info("嘿");[信息] [Foo:413] 嘿

但是如果在两者之间有一个辅助方法,实际调用者将是辅助方法,这不会提供太多信息.

log_info("嘿");[信息] [LoggingSupport:123] 嘿

在确定要打印的源位置时,有没有办法告诉日志系统从调用堆栈中删除一帧?

我想这是特定于实现的;我需要的是通过 Commons Logging 的 Log4J,但我有兴趣了解其他选项.

解决方案

替代答案.

可以通过使用方法让log4j排除helper类

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

并将帮助程序类指定为callerFQCN".

例如这里是一个使用助手的类:

public class TheClass {公共静态无效主(字符串...字符串){LoggingHelper.log("在日志助手中使用完整日志方法的消息.");LoggingHelper.logNotWorking("消息使用类信息方法");}}

和助手的代码:

公共类 LoggingHelper {私有静态记录器日志 = Logger.getLogger(LoggingHelper.class);公共静态无效日志(字符串消息){LOG.log(LoggingHelper.class.getCanonicalName(), Level.INFO, message, null);}公共静态无效 logNotWorking(字符串消息){LOG.info(消息);} }

第一种方法将输出您的预期结果.

Line(TheClass.main(TheClass.java:4)) 在日志助手中使用完整日志方法的消息.Line(LoggingHelper.logNotWorking(LoggingHelper.java:12)) 使用类信息方法的消息

当使用这种方法时,Log4j 会照常工作,如果不需要就避免计算堆栈跟踪.

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

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

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

解决方案

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.

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

08-01 00:50