Checking Filter Status before Constructing Log Messages

By using the Logging Application Block, you can query the filter status to determine whether a log message should be logged according to the filter configuration.

In this scenario, you want to avoid collecting context information for a log message if the current application block configuration indicates that the information will not be logged.

Create a LogEntry object that contains the information that will be submitted to the Logging Application Block. Call the ShouldLog method of the LogWriter class, passing to it the LogEntry object.

The following code shows how to create a LogEntry object and use the ShouldLog method. It assumes you have resolved an instance of the LogWriter class through the container and saved it in a variable named myLogWriter.

LogEntry logEntry = new LogEntry();
logEntry.Priority = 2;
logEntry.Categories.Add("UI Events");

if (myLogWriter.ShouldLog(logEntry))
  // Event will be logged according to current configuration. Perform operations (possibly
  // expensive) to gather additional information for the event to be logged. 
  // Event will not be logged. Your application can avoid the performance
  // penalty of collecting information for an event that will not be logged.

For information about resolving Enterprise Library objects in your applications, see Creating and Referencing Enterprise Library Objects.

You can query a specific filter type to determine whether a log message should be logged according to the configuration settings for that filter type.

The following code shows how to query the CategoryFilter.

ICollection<string> categories = new List<string>(0);
categories.Add("UI Events");

if (myLogWriter.GetFilter<CategoryFilter>().ShouldLog(categories))
  // Events with these categories should be logged.