7

I'm using the org.jboss.logging.Logger class, and seem to have come across an incongruity. When I have an error or warning, I simply have to use logger.error("error message") or logger.warn("warning message") and it will be displayed based on the settings in the jboss-log4j.xml file.

However, based on existing jboss code, this discussion, and this link, when trace is used you must first determine whether it is enabled using logger.isTraceEnabled(). Why does it appear that I have to this for trace alone?

josh-cain
  • 4,997
  • 7
  • 35
  • 55

1 Answers1

14

You don't "have to". It will work just fine without it. However, TRACE-level logging tends to to be massively verbose, and can take up a significant proportion of CPU time, even if it's ultimately not actually logged to the file. By putting the if check around the logging statement, you avoid that overhead.

I've seen other good quality codebases do the same for DEBUG and INFO level logging also, so it's not limited to TRACE.

See the section of the log4j manual relating to peformance.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • got it - so it's just a performance thing. Makes sense, especially for info level stuff that happens for every request – josh-cain Mar 01 '12 at 16:48
  • 3
    Just so you know, it depends on the logger you use. org.slf4j.impl.Log4jLoggerAdapter, for example, does this check internally, so you don't need to do it at all. IMHO it makes most sense for good loggers to do this check internally, especially as it already knows...The only performance gain you'd get is if your message was being built in a way that was less efficient than calling isTraceEnabled() (http://stackoverflow.com/questions/21281048/should-i-be-using-slf4j-istraceenabled-or-not) – ndtreviv Jul 16 '14 at 09:10
  • @ndtreviv the problem is in the overhead of string construction (if the string is constructed) and parameter overhead, if the string is passed by value, that will have to now be done all the way down to the trace level for every logger call even if your logger does the checking internally. If your log level is set to WARN, for example, and you're not checking isTraceEnabled, those trace log strings will still have to be constructed and passed by value to the logger for no reason; that's extra processing that doesn't need to be there. Whether its negligible or not is another question. – jbobbins Jul 17 '19 at 16:41
  • [here's a related question](https://stackoverflow.com/questions/10555409/logger-slf4j-advantages-of-formatting-with-instead-of-string-concatenation) on the use of `{}` formatting vs. String concatenation in slf4j. TL;DR, `{}` is lazy, so you don't pay the price of String building unless you actually log. – MyStackRunnethOver Feb 14 '22 at 21:22