Performance Impact of logging class name , method

2019-07-23 09:40发布

I am implementing logging in my java application , so that I can debug potential issues that might occur once the application goes in production.

Considering in such cases one wouldn't have the luxury of using an IDE , development tools (to run things in debug mode or step thorough code) , it would be really useful to log class name , method name and line number with each message.

I was searching the web for best practices for logging and I came across this article which says:

You should never include file name, class name and line number, although it’s very tempting. I have even seen empty log statements issued from the code:

log.info("");

because the programmer assumed that the line number will be a part of the logging pattern and he knew that “If empty logging message appears in 67th line of the file (in authenticate() method), it means that the user is authenticated”. Besides, logging class name, method name and/or line number has a serious performance impact.

I am trying to understand how logging class name , method name and line number degrade performance.

Is the above true for all logging frameworks or only some of them? (The author makes a reference to Logback in the same topic) . I am interested in knowing about performance impacts of doing something like this in Log4j.

1条回答
Root(大扎)
2楼-- · 2019-07-23 10:21

There are different concerns at play here. First of all, what is the impact of logging a simple string. This largely depends on the infrastructure you use. Recently I did run some benchmarks, and just logging a string to a file using the standard java logging API is extremely expensive. You're going to get better results using the log4j logging infrastructure, which my tests show are in the order of 15 or 20 times faster.

Now let's consider the file name and line number problem. As opposed to C, java doesn't have a __FILE__ and __LINE__ constant which are resolved by the compiler (or the preprocessor in case of C). If you want to log file name and line number, you have two options:

  1. You actually write such file name and line number yourself as constants. This may be acceptable for the filename, but the line number will change if you introduce any line above the one where you're logging, so you will have to go and change all the line numbers there. Not really reasonable
  2. You use java APIs to get a stack trace as mentioned here. This operation though is very expensive at runtime, and hence will slow down your program.
查看更多
登录 后发表回答