Walkthrough: Checking Filter Status Before Constructing Log Messages

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Enterprise Library information can be found at the Enterprise Library site.

This walkthrough demonstrates the steps to query the filter status to determine if a log message should be logged according to the filter configuration.

To reproduce the demonstration

  1. Create a LogEntry object that contains the log information.

    LogEntry logEntry = new LogEntry();
    logEntry.Priority = 2;
    logEntry.Categories.Add("Trace");
    logEntry.Categories.Add("UI Events");
    
    if (Logger.GetFilter<CategoryFilter>().ShouldLog(logEntry))
    {
      // Event will be logged according to currently configured filters.
      // 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.Priority = 2
    logEntry.Categories.Add("Trace")
    logEntry.Categories.Add("UI Events")
    
    If Logger.GetFilter(Of CategoryFilter)().ShouldLog(logEntry) Then
      ' Event will be logged according to currently configured filters.
      ' 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
    
  2. Call the Logger.ShouldLog method with the LogEntry object as the argument.

    LogEntry logEntry = new LogEntry();
    logEntry.Priority = 2;
    logEntry.Categories.Add("Trace");
    logEntry.Categories.Add("UI Events");
    
    if (Logger.ShouldLog(logEntry))
    {
      // Event will be logged according to currently configured filters.
    }
    else
    {
      // Event will not be logged. 
    }
    
    'Usage
    Dim logEntry As New LogEntry()logEntry.Priority = 2;
    logEntry.Priority = 2
    logEntry.Categories.Add("Trace")
    logEntry.Categories.Add("UI Events")
    
    If Logger.ShouldLog(logEntry) Then
      ' Event will be logged according to currently configured filters.
    Else
      ' Event will not be logged. 
    End If