“Logging with slf4j at warn level”, prevent the running “logger.debug(…”

huangapple go评论84阅读模式
英文:

Does "Logging with slf4j at warn level", prevent the running "logger.debug(..."

问题

关于根据日志级别处理日志行的问题,我有一个疑问;

如果日志级别设置为 WARN,那么它是否会调用进程“doSomeWorkwhichTakeslongTime()”?因为将一些类转换为 JSON 需要很长时间,我不想在生产环境中运行这个过程。要实现这一点,将日志级别设置为“warn”是否足够?
英文:

i've a question about processing log lines according to level like;

logger.debug("hello i am a log line not so neccessary, also log level is setted WARN and some complexProcessResult-> {}",
doSomeWorkwhichTakeslongTime());

If logger level sets to WARN so does it call the process "doSomeWorkwhichTakeslongTime()" because jsonizing some classes, take so much time, and i dont want to run this in production. To achieving this, is it enough setting the log level as "warn"?

答案1

得分: 0

不过,如果您使用这个特定的方法调用,那么更改日志级别对于是否调用doSomeWorkWhichTakesLongTime()不会产生任何影响。

它无法产生影响,因为Java语言规定在调用方法之前需要计算参数值。

有两种可能的解决方法:

一种“不太美观”的方法是使用 isDebugEnabled()

if (logger.isDebugEnabled()) {
    logger.debug("你好,我是一条不太必要的日志记录,日志级别也设置为WARN,还有一些复杂的处理结果-> {}", doSomeWorkwhichTakeslongTime());
}

另一种方法可能会稍微复杂一些,但更加友好:让繁重的工作发生在一个要么易于构建要么您已经可以访问的对象的toString()方法中:

logger.debug("你好,我是一条不太必要的日志记录,日志级别也设置为WARN,还有一些复杂的处理结果-> {}", someObjectThatDescribesTheOutput)

并且让someObjectThatDescribesTheOutput拥有类似这样的toString方法:

public String toString() {
    return doSomeWorkwhichTakeslongTime();
}
英文:

No, if you use this specific method call, then changing the log level would have no impact on whether or not doSomeWorkWhichTakesLongTime() is being called or not.

It can't have an effect, because the Java language specifies that the parameter values need to be computed before the method is called.

There are two possible workarounds:

The "ugly" one is to use isDebugEnabled():

if (logger.isDebugEnabled()) {
    logger.debug("hello i am a log line not so neccessary, also log level is setted WARN and some complexProcessResult-> {}", doSomeWorkwhichTakeslongTime());
}

The other one is a bit trickier, but potentially nicer: Have the heavy lifting happen in the toString() of an object that is either cheap to construct or that you have accessible anyway:

logger.debug("hello i am a log line not so neccessary, also log level is setted WARN and some complexProcessResult-> {}", someObjectThatDescribesTheOutput)

and have someObjectThatDescribesTheOutput have a toString method a little like this:

public String toString() {
    return doSomeWorkwhichTakeslongTime();
}

huangapple
  • 本文由 发表于 2020年10月19日 19:36:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/64426515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定