避免启用Log4j/Slf4j调试检查 [英] Avoid Log4j/Slf4j debug enabled checks

查看:106
本文介绍了避免启用Log4j/Slf4j调试检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几乎在每个项目中,我都使用Log4j或Slf4j进行logback记录事件,几乎在所有地方我都必须编写类似的内容

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

有时您看不到所有这些日志记录代码的实际方法逻辑. 我无法删除log.isDebugEnabled()检查,因为即使未启用调试(或任何级别),即使我将Slf4j与{}功能一起使用,也可能会计算并删除某些日志信息.

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?

如果我不能使用Java 8并且正在使用Slf4j api,那么Log4j2不可用,有哪些可能的选择?

What are possible options if I cannot use Java 8 and I'm using Slf4j api, so Log4j2 is not available?

推荐答案

通过使用Log4j2和Java 8,您可以按照调试(消息,供应商)例如

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());

如果您不能使用log4j2或java 8,请查看

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.

这篇关于避免启用Log4j/Slf4j调试检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆