Logging Application Block Details
1. Introduction
The logging application block simplifies the implementation of common logging functions. It allows the developer to write information to a variety of locations based on the configuration used. These include
- The event log
- An e-mail message
- A database
- A message queue
- A text file
- A WMI event
- Custom locations using application block extension points
The Logging Application Block provides a consistent interface for logging information to any destination rather then in application code. Configuration settings determine whether the application block writes the logging information and the location it is written to.
The primary goal of the logging application block is to allow a developer
to focus on when and why a message should get logged and to allow an administrator
to determine how, where and if the message gets logged. The Logging Application
Block achieves its design goal by exposing a service facade; in this case, it
is the Logger class.
The Logger interface only exposes one method for logging
information - a static or shared write method.
2. When to use the Logging Application Block
The Logging Application Block should be used when:
- There is a requirement to log information to the event log, e-mail, a database, a message queue, windows management instrumentation (WMI), or a file.
- There is a need to filter logging messages based on category or priority.
- The messages need to be formatted.
- There is a requirement to change the destination of the message without changing the application code.
- A simple, consistent interface for logging within the application and across the enterprise is required.
The Logging application block can be used to easily set up an enterprise wide central logging system for all applications. All applications could be easily configured to send messages to a message queue that is centrally monitored.
Note: The Logging Application Block formatters do not encrypt logging information. Trace listener destinations receive logging information as clear text.
3. Usage
References
To use the Logging Application Block add the following reference assemblies to the project or to the GAC
Microsoft.Practices.EnterpriseLibrary.Logging.dll
and the core assemblies
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.ObjectBuilder.dll
If Extra Information Providers are used add Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation.dll
to the project or to the GAC.
If the Logging Application Block uses the database trace listener
then the Data Access Application Block needs to be
added to the project or
to the GAC. Microsoft.Practices.EnterpriseLibrary.Logging.Database.dll
Namespaces
The following namespaces need to be included in the classes that use the Logging block.
Imports System.DiagnosticsImports Microsoft.Practices.EnterpriseLibrary.Logging
If there is a requirement for logging extra information or additional context information the add.
ImportsMicrosoft.Practices.EnterpriseLibrary.Logging.ExtraInformation
If there is a requirement for filters in the application add the following
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Filters
If using the FormatterDatabaseTraceListener class include the following
Imports Microsoft.Practices.EnterpriseLibrary.Logging.Database
4. Logging application block class diagram
5. Encapsulation of common logging information using LogEntry class
Definition
The LogEntry class encapsulates content and associated properties
for the information an application sends to the application block for logging.
Create new log entries and set properties such as the message, title, priority, and event ID. Other properties, such as the process name, process ID, and Thread Id, are populated by the Logging Application Block.
Method
The LogEntry class does not have any methods but contains a number of properties that can be set.
Example
LogEntry
' Imports the main classes required for using the Logging Application Block Imports Microsoft.Practices.EnterpriseLibrary.Logging ' This import is required for the classes that implement IExtraInformationProvider ' (for extended properties) Imports Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation Dim log As New LogEntry log.EventId = 102 log.Priority = 1 'Low priority log.Severity = TraceEventType.Information log.Title = "Example 3" log.Categories.Add("Debugging")
log.Message = "You just ran example number 3, congratulations"
6. Populating a log message with additional context information
Definition
The ExtraInformation providers gather context information
that is useful but not always necessary because it is expensive to collect.
Examples are stack trace information and COM+ information.
The ExtendedProperties property of the LogEntry class can
be used to
pass the collection of properties to the Write method of the Logger
class.
The following classes implement IExtraInformationprovider
to populate a collection of properties.
ComPlusInformationProvider. This class populates the collection with the following commonly needed COM+ diagnostic informatiom:
Activity ID - Returns the COM+ Activity ID.
Application ID - Returns the COM+ Application ID.
Transaction ID - Returns the COM+ Direct Caller Name.
Direct caller account name - Returns the COM+ Original Caller Account Name.
Original caller account name - Returns the COM+ Transaction ID.DebugInformationProvider.This class populates the collection with a property containing the current stack trace information.ManagedSecurityContextInformationProvider.This class populates the collection with the following commonly needed security-related information diagnostic information from the managed runtime:
Authentication type - The authentication type.
Current identity name - The identity's name.
Authentication status - The IsAuthenticated flag.UnmanagedSecurityContextInformationProvider.This class populates the collection with the following commonly needed unmanaged security-related information:
Current user - Gets the current user.
Process account name - Gets the account name of the process.
Public Sub PopulateDictionary ( ByVal dict As System.Collections.Generic.IDictionary
( Of String, Object ) )
Member of: Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation.ManagedSecurity
ContextInformationProvider
Summary: Populates an System.Collections.Generic.IDictionary`2 with helpful
diagnostic information.
Parameters: dict: Dictionary used to populate the Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation.ManagedSecurity
ContextInformationProvider
Example
ComPlusInformationProvider
' Imports the main classes required for using the Logging Application Block Imports Microsoft.Practices.EnterpriseLibrary.Logging ' This import is required for the classes that implement IExtraInformationProvider ' (for extended properties)
Imports Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation Dim log As New LogEntry ' Create a dictionary to hold some additional custom properties. Dim extraProperties As New Dictionary(Of String, Object)() ' Create an instance of one of the supplied context information providers ' and populate our dictionary with the properties it provides. ' Note: Retrieving extra context information is an additional performance ' cost so it is not done by default. Dim informationProvider As New ComPlusInformationProvider ' Set some of our own custom properties. extraProperties.Add("MouseWheelExists", My.Computer.Mouse.WheelExists) informationProvider.PopulateDictionary(extraProperties) log.ExtendedProperties = extraProperties
7. Logging by calling shared method write of Logger class ( Logging Facade )
Definition
The Logger class is a facade that sends a log entry to one
or more destinations. The client code or application sends the information to
the Logger instance, which then sends the LogEntry
to an instance of the LogWriter class.
You use the static method Write on the Logger class to log
information. The Write method has multiple overloads to support the different
amounts of information an application may log.
Note: Whenever a Log Entry object fails within the
LogWriter instance, the LogWriter instance writes a LogEntry
object to the ErrorSource special trace source. The EventID is
always the LogWriterFailureEventID. The EventID number is 6352.
Public Shared Sub Write ( ByVal log As Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry
) - ( 19 overloads )
Member of: Microsoft.Practices.EnterpriseLibrary.Logging.Logger
Summary: Writes a new log entry as defined in the Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry parameter.
Parameters: log: Log entry object to write.
Note : Other overload methods construct a LogEntry
instance based on the parameters passed
Example
Write
' Imports the main classes required for using the Logging Application Block Imports Microsoft.Practices.EnterpriseLibrary.Logging Dim log As New LogEntry log.EventId = 101 log.Priority = 4 'High Priority log.Severity = TraceEventType.Error log.Title = "Example 2" log.Categories.Add("Debugging") log.Categories.Add("Errors") log.Message = "Some disastrous event occured!" Logger.Write ( log )
8. Tracing using the Logging Application Block
Definition
Logging is the act of publishing a LogEntry message to one
or more endpoints, tracing is concerned with "telling a story"
by logging and correlating multiple messages that occur in a particular activity
in an application.
Tracing logs information at the start and end of particular activity at selected points in the application.
Tracing associates all events between the start and end of an activity with
an ActivityID property and a category.
The ActivityID property correlates log entries that are
written during the execution of an activity.
The end time of the activity is logged using the same category when the Tracer object is disposed. The automatic disposal behaviour of the using statement causes the end time to be logged when the scope of the using statement is exited.
Note : Tracing can be nested.
Method
Create an Instance of the Tracer class.
Public Sub New ( ByVal operation As String ) (4 overloads )
Member of: Microsoft.Practices.EnterpriseLibrary.Logging.Tracer
Summary: Initialises a new instance of the Microsoft.Practices.EnterpriseLibrary.Logging.Tracer
class with the given logical operation name.
Parameters: operation: The operation for the Microsoft.Practices.EnterpriseLibrary.Logging.Tracer
Remarks: If an existing activity id is already set, it will be kept. Otherwise,
a new activity id will be created.
Example
Using (New Tracer("Debugging"))
DoDataAccess()
End Using
Note: The preceding code will result in the Tracer object generating a unique identifier for the activity. You can use this activity identifier to correlate all log entries for particular execution of an activity. Alternatively, you can specify the activity identifier in the code that constructs the Tracer object. The application block uses the .NET Framework CorrelationManager class to maintain the activity identifier.
9. Declaring the Logging Application Block configuration section-handler
Section
Add the following configuration section
Example
<configSections><section name="loggingConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" />
</configSections>
10. Formatters
Section
Formatters : The Logging Application Block can configure formatters that control how the logged message is displayed. The following two types of formatter are available.
TextFormatterconverts a log entry into a text string. The contents of the string are determined by replacing tokens in the TextFormatter'stemplateproperty. Each Token maps to a property in the LogEntry class
Default TextFormatter Template - modify this template or add new templates
Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Machine: {machine}
Application Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
Extended Properties: {dictionary({key} - {value} )}
BinaryLogFormatteruses the .NET FrameworkBinaryFormatterto serialize and de-serialize the log entry in binary format. BinaryLogFormatter is required when using the Msmq trace listener with the Message Queuing distributor service.
This element specifies formatters that format LogEntry objects. Formatters
are used by formatting-aware trace listeners.
Note: Use Enterprise Library Configuration Console for Configuration.
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.BinaryLogFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
name="Binary Formatter" />
</formatters>
<add template="Timestamp: {timestamp}, Category: {category}, Priority: {priority}, EventId: {eventid}, Severity: {severity}, Message: {message}"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
name="Simple Text Formatter" />
</formatters>
11. Trace Listeners
Section
listeners: Trace listeners receive log entries and write them to the appropriate destinations. The following types of listener are available in the Logging Application Block
EmailTrace Listener. This is a trace listener that sends out log entries as e-mail.Flat FileTrace Listener. This is a trace listener that writes log entries to a text file.Database Trace Listener. This is a trace listener that writes formatted log entries to a database.FormattedEvent LogTraceListener. This is a trace listener that formats log entries and writes them to an event log.MsmqTraceListener. This is a trace listener that writes log entries to a message queue.System DiagnosticsTraceListener. This is one of the .NET Framework trace listeners such as theConsole Trace Listener.WMITraceListener. This is atrace listener that raises a WMI management event for each log entry received.Rolling Flat File Trace Listener. This is a trace listener that creates a new log file depending on the current log file's age and/or size.XML TraceListener. This trace listener is used to integrate the Logging Application Block with applications that use WCF.
Note: Use Enterprise Library Configuration Console for Configuration.
<add toAddress="to@example.com"
fromAddress="from@example.com"
subjectLineStarter="test end"
subjectLineEnder="test start"
smtpServer="127.0.0.1"
smtpPort="25"
formatter=" Simple Text Formatter "
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration. EmailTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
traceOutputOptions="None"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.EmailTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
name="Email TraceListener" />
</listeners>
<add fileName="LoggingDemo.log"
header="----------------------------------------"
footer="----------------------------------------"
formatter="Detailed Text Formatter"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration .FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
traceOutputOptions="None"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null"
name="FlatFile TraceListener" />
</listeners>
<listeners>
<add databaseInstanceName="LocalSqlServer"
writeLogStoredProcName="WriteLog"
addCategoryStoredProcName="AddCategory"
formatter=""
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData,
Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=3.1.0.0,
Culture=neutral, PublicKeyToken=null"
traceOutputOptions="None"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener,
Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=3.1.0.0,
Culture=neutral, PublicKeyToken=null"
name="Database
Trace Listener" />
</listeners>
The Formatters are attributes of Trace Listeners
The meanings of the values for the traceOutputOptions attribute are
as follows:
Callstack. Write the call stack, which is represented by the return value of theSystem.Environment.StackTraceproperty.DateTime. Write the date and time.LogicalOperationStack. Write the logical operation stack, which is represented by the return value of theSystem.Diagnostics.CorrelationManager.LogicalOperationStackproperty.None. Do not write any elements.ProcessId. Write the process identity, which is represented by the return value theSystem.Diagnostics.Process.Idproperty.ThreadId. Write theThreadIdentity, which is represented by the return value theSystem.Threading.Thread.ManagedThreadIdproperty for the current thread.Timestamp. Write the timestamp, which is represented by the return value of theSystem.Diagnostics.Stopwatch.GetTimeStampmethod.
Note: A default database script for the Database Trace Listener is shipped with the Logging Application Block. It can be found at "<Enterprise Library Install Dir>\App Blocks\Src\Logging\TraceListeners\Database\Scripts".
12. Category Sources
Section
categorySources: This element defines the categories that route log entries to trace listeners. The categorySources element is a child
of the loggingConfiguration element.
The listeners element specifies the trace listeners that the log entries
are routed to. This element is optional.
Note: Use Enterprise Library Configuration Console for Configuration.
<categorySources>
<add
switchValue="All"
name="Debugging">
<listeners>
<add
name="FlatFile
TraceListener" />
</listeners>
</add>
<add
switchValue="All"
name="Errors">
<listeners>
<add
name="FlatFile
TraceListener" />
</listeners>
</add>
<add
switchValue="All"
name="General">
<listeners>
<add
name="FlatFile
&
TraceListener" />
</listeners>
</add>
</categorySources>
The following switchValue settings can be used:
Activity Tracing. Allows theStop,Start,Suspend,Transfer, andResumeevents through.All. Allows all events through.Critical. Allows onlyCriticalevents through. A critical event is a fatal error or application crash.Error. AllowsCriticalandErrorevents through. AnErrorevent is a recoverable error.Information. AllowsCritical,Error,Warning, andInformationevents through. An information event is an informational message.Off. Does not allow any events through.Verbose. AllowsCritical,Error,Warning,Information, andVerboseevents through. AVerboseevent is a debugging trace.Warning. AllowsCritical,Error, andWarningevents through. AWarningevent is a non-critical problem.
13. Special Sources
Section
specialSources: The Logging Errors and Warnings special source receives log entries for errors and warnings that occur during the logging process. The Unprocessed Category special source receives log entries that are assigned to categories that are not processed by a category source. The All Events special source receives all log entries.
Note: Use Enterprise Library Configuration Console for Configuration.
<specialSources>
<allEvents
switchValue="All"
name="All
Events" />
<notProcessed
switchValue="All"
name="Unprocessed
Category" />
<errors
switchValue="All"
name="Logging
Errors & Warnings">
<listeners>
<add
name="FlatFile
&
TraceListener" />
</listeners>
</errors>
</specialSources>
14. Filters
Section
logFilters: This element configures the filters that process the LogEntry before it is
routed to the trace sources. Each filter prevents the specified type of
message from being logged.
Note: Use Enterprise Library Configuration Console for Configuration.
<logFilters>
<add
categoryFilterMode="AllowAllExceptDenied"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.CategoryFilter,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral,
PublicKeyToken=null"
name="Category
Filter" />
<add
enabled="false"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.LogEnabledFilter,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral,
PublicKeyToken=null"
name="LogEnabled
Filter" />
<add
minimumPriority="1"
maximumPriority="5"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.PriorityFilter,
Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral,
PublicKeyToken=null"
name="Priority Filter" />
</logFilters>
15. Deployment
Guideline
Applications that use the Logging Application Block can be deployed in one of two configurations:
- They can be deployed as private assemblies in the application folder hierarchy.
- They can be deployed as shared assemblies in any file system location or in the global assembly cache.
16. References
http://msdn2.microsoft.com/en-us/library/aa480464.aspx
Download Enterprise Application Block 3.1 www.microsoft.com/downloads/details.aspx?familyid=4c557c63-708f-4280-8f0c-637481c31718&displaylang=en
17. Demo source code
The sample below demonstrates some common uses of the Logging Block. In order to run this demonstration the following prerequisites are needed.
- Windows Message Queue (for MsmqTraceListener and Distributor Service)
- Microsoft Enterprise Library 3.1 May 2007
To run the sample simply unzip to a known location and open the file loggingDemo.sln in Visual Studio .NET then read the file Readme.txt before running