Share via


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.

Typical Goals

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.

Solution

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("Trace");
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. 
}
else
{
  // Event will not be logged. Your application can avoid the performance
  // penalty of collecting information for an event that will not be logged.
}
'Usage
Dim logEntry As New LogEntry()
logEntry.Priority = 2
logEntry.Categories.Add("Trace")
logEntry.Categories.Add("UI Events")

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

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

Usage Notes

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("Trace");
categories.Add("UI Events");

if (myLogWriter.GetFilter<CategoryFilter>().ShouldLog(categories))
{
  // Events with these categories should be logged. 
}
'Usage
Dim categories As ICollection(Of String) = New List(Of String)(0)
categories.Add("Trace")
categories.Add("UI Events")

If myLogWriter.GetFilter(Of CategoryFilter)().ShouldLog(categories) Then
  ' Events with these categories should be logged.
End If