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:
- It clutters the code
- 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)
- Internally, the Write method already calls
ShouldLog
so if you are logging then ShouldLog
will be called twice for every message logged