Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4net performance: should i check log level before trying to log?

Tags:

c#

log4net

Would you expect better performance from A) or B) below if log level in the log4net config is set to Info level? Will _log.Debug on its own execute more code and take longer?

A)

if(_log.IsDebugEnabled)
  _log.Debug("some message");

B)

_log.Debug("some message");
like image 555
DayTwo Avatar asked Sep 09 '10 09:09

DayTwo


People also ask

What is level value in log4net?

log4net offers the following log levels, in increasing order of priority: ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF. The ALL level logs everything and the OFF level logs nothing.

Is log4net thread safe?

Is log4net thread-safe? Yes, log4net is thread-safe.

Why do we use logger in C#?

Logging levels are used to filter logging output, tailoring the amount of data output to the situation in hand. Each logging level is associated with the type of data logged. DEBUG, INFO, and TRACE events are typically non-error conditions that report on the behavior of an application.


2 Answers

In this case, I'd use B.

However, if constructing the log message (the argument to log.Debug) may take a while - involving significant string concatenation, for example - then I would go for A. It will end up performing the same test twice in the "yes, log it" case, but it won't need to construct the log message in the "no, don't log it" case.

like image 172
Jon Skeet Avatar answered Sep 25 '22 03:09

Jon Skeet


I would choose option B unless the log message itself takes a long time to construct. The performance gain for the usual case is negligible or doesn't even exist. Internally, log4net does the same check so you won't change anything by doing it yourself.

But as I said, option A may be a good idea in a situation like this:

if (_log.IsDebugEnabled())
{
    var message = createComplicatedLogMessageThatTakesALotOfTime();
    _log.Debug(message);
}

For all other cases, it just adds three more lines for every message you log which just isn't worth the effort.

like image 27
Ronald Wildenberg Avatar answered Sep 25 '22 03:09

Ronald Wildenberg