Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the LogWriter.ShouldLog(LogEntry) method behaviour based on?

What is the LogWriter.ShouldLog(..) method behaviour based on? Or what is the real intention of its usage? Its documentation page is rather sparse and doesn't provide much insight. Quoting it:

Queries whether a LogEntry shold[sic] be logged.

(Complete with same typo in all versions of the Enterprise Library, makes me wonder if the authors paid much attention to it.)

The method seems rather ethereal to me. Should I always check it before logging?

Currently I only check LogWriter.IsLoggingEnabled(..) which is based on an explicit setting in configuration. This represents a concrete scenario: the logging is either turned on or off.

like image 896
John K Avatar asked Apr 05 '11 15:04

John K


1 Answers

Behavior

LogWriter.ShouldLog( LogEntry logEntry ) queries all of the configured filters against the data in the LogEntry to determine if the specific LogEntry should be logged. If all filters return true (for ShouldLog) then the LogEntry would be logged if the Write method were called. The out of the box filters are Category, Priority, and LoggingEnabled although you can create your own custom filters.

The IsLoggingEnabled check in contrast just checks one filter whereas the ShouldLog call checks all filters (including IsLoggingEnabled).

Intention

The intention of the call is to allow the developer to avoid expensive operations if the LogEntry will not be logged. What "expensive" is will depend on the application and requirements. e.g. excessive string manipulation in a tight loop or perhaps an out of process call to retrieve some information (although that might be a good candidate for caching!).

Should I always check it before logging?

In general, I would avoid calling ShouldLog unless there is a compelling reason to do otherwise.

I can think of a few reasons:

  1. It clutters the code
  2. If you try to de-clutter the code with a helper method then the LogEntry would usually be fully populated so you probably wouldn't have avoided any operations anyway (although you could pass in a delegate and not invoke it but I'm not sure that is making things simpler)
  3. Internally, the Write method already calls ShouldLog so if you are logging then ShouldLog will be called twice for every message logged
like image 83
Randy supports Monica Avatar answered Sep 28 '22 03:09

Randy supports Monica