本文介绍了间接调用log4j的日志方法(来自辅助方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将logger.debug(...)调用放入一个帮助器方法,并从需要编写日志的任何地方调用该辅助方法。虽然这大多数工作正常,但日志条目本身显示了辅助方法作为调用的来源,这是可以理解的,因为log4j不知道我使用辅助方法进行日志记录。

I'd like to put the logger.debug(...) call into a helper method, and call that helper method from anywhere that needs to write the log. While this mostly works fine, the log entry itself shows the helper method as the source of the call, which is understandable since log4j isn't aware of me using a helper method for logging.

有没有办法告诉它在找出logger.debug(...)调用的来源时跳过辅助方法,而是使用它的调用者?

Is there any way to tell it to skip the helper method when figuring out the source of the logger.debug(...) call and instead use its caller?

按来源,我的意思是org.apache.log4j.PatternLayout的%F:%L

By source, I mean %F:%L of org.apache.log4j.PatternLayout: https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

为了说明我的意思,这里是一个示例堆栈跟踪:

To illustrate what I mean, here's an example stack trace:

1. logger.debug(msg, throwable)
2. logHelper(logger, msg, throwable) <-- currently shows as the source of the call, since it calls logger.debug directly
3. someFunction <-- where the real logable event occurs, so I'd want this to be logged as the source

我这样做的原因是因为如果日志级别是INFO,我想仅通过名称(e.toString)记录异常,或者如果级别是DEBUG则使用完整堆栈跟踪。我愿意接受替代方案的建议。

The reason I'm doing this is because I'd like an exception logged only by name (e.toString) if the log level is INFO, or with a full stack trace if the level is DEBUG. I'm open to suggestions for alternatives.

谢谢! :)

推荐答案

对于log4j2,您可以编写一个简单的包装类或生成一个Webel建议的类。请参阅我对log4j2的回答:

For log4j2, you can write a simple wrapper class or generate one as Webel suggests. See my answer for log4j2:https://stackoverflow.com/a/39045963/116810

这篇关于间接调用log4j的日志方法(来自辅助方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 12:43