One of the things you can configure in the Enterprise Library logging block is a custom filter. This is a class that examines log entries prior to them being written and can prevent a log entry from being written.
Microsoft's documentation on this subject is pretty lacking, so here's what you need to be aware of:
1) You need to inherit from LogFilter, even though the documentation says to implement ILogFilter. LogFilter inherits from ILogFilter.
2) You have to decorate your derivation with a ConfigurationElementType attribute and declare the type (in the attribute, see the code sample below) as CustomLogFilterData. The class will compile without this, but won't load in the configuration editor. The message from the configuration editor is misleading, it claims you didn't derive from LogFilter.
3) The base class lacks a parameterless constructor, so, you have to supply a constructor that takes a string and calls the base class's corresponding constructor.
4) Although not part of the contract with the base class/interface, you need to supply a constructor that takes a NameValueCollection. This contains the parameters that are defined in the configuration editor. The class will compile without this, but can't be instantiated at runtime without it.
Here's a sample:
using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;
namespace LoggingTest {
[ConfigurationElementType(typeof(CustomLogFilterData))]
public class AdministrativeFilter : LogFilter {
public AdministrativeFilter(string Name) : base(Name) {}
public AdministrativeFilter(NameValueCollection nvPairs) : this("AdministrativeFilter") {}
public override bool Filter(LogEntry log) {
if (
log.Severity == TraceEventType.Critical ||
log.Severity == TraceEventType.Error ||
log.Severity == TraceEventType.Start ||
log.Severity == TraceEventType.Stop ||
log.Severity == TraceEventType.Warning)
{
return true;
}
return false;
}
}
}
The big problem with all this is the whole filter concept in the logging block. Filters (custom and otherwise) are global. Whatever filters you define apply to all destinations. What you really need (and EIF had) is filters by destination. This way, you can have a log file filled with tracing detail while only sending the important stuff to the event log. If you send the detail to the event log, the event log becomes impossible to work with and the volume of messages may overwrite old messages that you need.