问题描述
几乎在每个项目中,我都使用log4j或slf4j,带有logback到log Events,几乎到处都必须写
if (log.isDebugEnabled()) { log.debug("I'm here doing this stuff"); }
有时您没有看到所有这些记录代码的实际方法逻辑. 我无法删除log.isDebugEnabled()检查,因为即使我将SLF4J与{}一起使用,如果不启用调试(或任何级别),也可能会计算和删除一些日志信息.
log.debug("Here is the data: {}", calculateDataFromSeveralDataSourcesDuh());
这是一个问题:有没有一种方法来推迟日志信息计算,因此仅在启用适当的日志级别的情况下才能在没有应用程序代码中进行检查时进行计算?
如果我不能使用Java 8并且我使用的是SLF4J API,那么有什么可能的选项,因此Log4j2不可用?
推荐答案
通过使用log4j2和java 8,您可以轻松地使用lambdas,如所述在这里,在您的情况下,使用
,如果您不能使用log4j2或java 8,请查看对象渲染
问题描述
Almost in every project I use either Log4j or Slf4j with logback to log events and almost everywhere I have to write something like
if (log.isDebugEnabled()) { log.debug("I'm here doing this stuff"); }
Sometimes you don't see actual method logic with all these logging code. I cannot remove log.isDebugEnabled() checks because even if I use Slf4j with {} feature some log information might be calculated and dropped if debug (or whatever level) is not enabled.
log.debug("Here is the data: {}", calculateDataFromSeveralDataSourcesDuh());
Here is the question: Is there a way to postpone log info calculation, so it is calculated only when appropriate log level is enabled without checks in application code?
What are possible options if I cannot use Java 8 and I'm using Slf4j api, so Log4j2 is not available?
推荐答案
By using Log4j2 and Java 8, you can easily make use of lambdas as described here, so in your case using debug(Message, Supplier) e.g.
log.debug("Here is the data: {}", () -> calculateDataFromSeveralDataSourcesDuh());
In case you can't use log4j2 or java 8, have a look at the concept of object rendering in log4j. You can set up your own object renderer for specific classes, whose construction would be cheap in comparison to rendering it (involving your calculateDataFromSeveralDataSourcesDuh call). Assuming only parts of your debug information is costly to compute, it might be worthwhile to identify those situations and create custom classes (and corresponding object renderers) for them.