Programatic Configuraton - Enterprise Library (v2.0) Logging Block
The following code sample shows how to configure the Enterprise Library Logging Block programatically without the help of ObjectBuilder. To create a working LogWriter instance with your own settings you need to create the following objects:
- A Formatter which contains a valid message template
- A LogSource which has a name (Category) contains a colleciton of Listeners (Sinks) along with the Formatter.
- A collection LogSources with the category as key and the LogSource object as value
To use this logger you can call
ConfigLessLogger.Error("Hello world of config by code.");
The error is written to the Windows Event Application Event Log:
Timestamp: 16.02.2006 23:33:41
Message: Hello World of dynamic object creation
Category: Errors
I have improved my original ConfigLessLogger sample with the very helpful comments from David Hayden who blogs about the Enterprise Library (mainly IConfigurationSource and Logging Block).
ConfigLessLoger.cs
using System;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
namespace MyApp.Logging
{
public class ConfigLessLogger
{
private static LogWriter writer; // Instance is created in static ctor which is thread safe
const string EventLogSource = "Code Source"; // Event Log Source name
const string ErrorCategory = "Errors"; // We have only one message category: Errors
static ConfigLessLogger()
{
writer = CreateLogWriterFromCode(); // static ctor is thread safe according to ECMA standard section 9.5.3
}
static private LogWriter CreateLogWriterFromCode()
{
// This is our message template for any Sink you add below in our case the Windows Event Log
TextFormatter formatter = new TextFormatter("Timestamp: {timestamp}{newline}" +
"Message: {message}{newline}" +
"Category: {category}{newline}" );
LogSource emptyTraceSource = new LogSource("none");
LogSource errorsTraceSource = new LogSource(ErrorCategory, System.Diagnostics.SourceLevels.All);
// Create for all Errors a Listener which writes the messages to the Windows Event Log
// with the Event Log Source Property "Code Source". The message format is specified by
// the TextFormatter which is in our case the template above.
errorsTraceSource.Listeners.Add(new FormattedEventLogTraceListener(EventLogSource, formatter));
IDictionary<string, LogSource> traceSources = new Dictionary<string, LogSource>();
// Add to Category "Error" our EventLog Listener with the corresponding category in it.
traceSources.Add(errorsTraceSource.Name, errorsTraceSource);
return new LogWriter(new ILogFilter[0], // ICollection filters
traceSources, // IDictionary<string, LogSource> traceSources
emptyTraceSource, // LogSource allEventsTraceSource
emptyTraceSource, // LogSource notProcessedTraceSource
errorsTraceSource, // LogSource errorsTraceSource
ErrorCategory, // string defaultCategory
false, // bool tracingEnabled
true); // bool logWarningsWhenNoCategoriesMatch
}
///
/// Write an Error message to the Windows Event Log with an message template specifed in code
///
/// Error message to log
public static void Error(string message)
{
LogEntry ent = new LogEntry();
ent.Categories.Add(ErrorCategory); // To use another category use traceSources.Add("OtherCat", Listener);
ent.Message = message;
ent.Severity = System.Diagnostics.TraceEventType.Error;
writer.Write(ent);
}
}
}
