Enterprise Library 2.0 Tip (4): How to Configure Logging Application Block in a programmatic way
In this series of tips (1) and tips (2), respectively, the use of external configuration files, the use of database records configuration information Two methods, do not know if you have not used any configuration files, and do not use the database to directly use the programming method to achieve it? This article will show you how to configure the logging Application block using a programmatic approach. First we need to look at some of the more important objects in logging Application Block:
1. Logformatter
Format objects, Logformatter have TextFormatter and BinaryFormatter two, in most cases we will use the TextFormatter, which is created by a template, a complete template format as follows:
Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {machine}{newline}
Application Domain: {appDomain}{newline}
Process Id: {processId}{newline}
Process Name: {processName}{newline}
Win32 Thread Id: {win32ThreadId}{newline}
Thread Name: {threadName}{newline}
Extended Properties: {dictionary({key} - {value})}{newline}
This does not specifically explain the meaning of each item, you can refer to the documentation, sample code:
const string Template = "Timestamp: {timestamp}{newline}" +
"Message: {message}{newline}" +
"Category: {category}{newline}" +
"Machine: {machine}{newline}";
TextFormatter formatter = new TextFormatter(Template);
2. TraceListener
TraceListener provides a logging service that specifies where the log will be logged, the database, or a text file, and the Enterprise library provides 7
Tracelistener:database TraceListener, Email TraceListener, Flat File TraceListener, Formatter Event Log TraceListener, MSMQ TraceListener, System diagnostics TraceListener, WMI Trace Listener. Each TraceListener requires a logformatter to format the recorded information, such as creating a Flatfiletracelistener instance:
const string LogFilePath = @"d:\\share\\messages.log";
FlatFileTraceListener logFileListener =
new FlatFileTraceListener(LogFilePath,"----------","----------", formatter);
The formatter here is the TextFormatter object that was created above.
3. Logsource
Logsource is actually a collection of TraceListener, the Enterprise library allows you to record different places for different log information, so you can add multiple TraceListener to Logsource:
Logsource Mainlogsource =
New Logsource ("Mainlogsource", Sourcelevels.all);
MAINLOGSOURCE.LISTENERS.ADD (Logfilelistener);