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<ILogFilter> filters
traceSources, // IDictionary<string, LogSource> traceSources
emptyTraceSource, // LogSource allEventsTraceSource
emptyTraceSource, // LogSource notProcessedTraceSource
errorsTraceSource, // LogSource errorsTraceSource
ErrorCategory, // string defaultCategory
false, // bool tracingEnabled
true); // bool logWarningsWhenNoCategoriesMatch
}
/// <summary>
/// Write an Error message to the Windows Event Log with an message template specifed in code
/// </summary>
/// <param name="message">Error message to log</param>
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);
}
}
}