Introduction
The Microsoft Enterprise Library is a collection of reusable software components (application blocks) designed to assist software developers with common enterprise development cross-cutting concerns, such as logging, validation, data access, exception handling, and many others.
Enterprise Library comes with an easy configuration tool that makes it easier to plug required application blocks into your application. Most developers, though, plug in these application blocks programmatically since this approach is also easy.
What are application blocks?
The definition we use is “pluggable and reusable software components designed to assist developers with common enterprise development challenges.” Application blocks help address the kinds of problems developers commonly face from one line-of-business project to the next.
Their design encapsulates the Microsoft recommended practices for Microsoft .NET Framework-based applications, and developers can add them to .NET based applications so as to configure them quickly and easily.
In this article, we are going to explore the Logging block of the Microsoft Enterprise Library.
How
We have to install Enterprise Library – Logging Application Block from NuGet Packages.
Once it is installed successfully, the below references and packages will be added to the application.
Microsoft Enterprise Library Configuration Tool
This tool will be used to configure different blocks for the application. Now, we need to install the Microsoft Enterprise Library from the below URL by following the installation instructions.
Microsoft Enterprise Library 6
As in this article, we are just going to discuss regarding the Logging Application Block, we will now configure the logging configure details for our application.
Please follow the configuration steps below:
Right click on the App.config >> Open with Enterprise Library Application Block Console.
If it is not available in the list, you can add it manually by clicking on the Add button.
We can log the messages in different file types. In this article, we are going to log in simple text file (Rolling Flat File Listener) and Windows Event Log (Event Log Listener).
Basic Field Information
- File Name - Log File name and path of the file.
- Formatter Name - Formatter of the log.
- Template - Template of the log; we can set as per our requirement.
- Roll Interval - Interval of the Log; as we have selected Day, it will create log files on daily basis.
Now, we are done with our configuration. All the above configuration will generate the below sections in our App.config.
You can directly add the below configuration blocks to your App.config under <configuration> section if you don’t want to configure through the console.
- <configSections>
- <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
- </configSections>
-
- <loggingConfiguration name="" tracingEnabled="false" defaultCategory="General"
- logWarningsWhenNoCategoriesMatch="false">
-
- <listeners>
- <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
- fileName="RollingFlatFile.log"
- footer="----------------------------------" formatter="Text Formatter"
- header="" rollInterval="Day"
- traceOutputOptions="DateTime, Timestamp" filter="All" />
-
- <add name="Event Log Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" source="Application" formatter="Text Formatter" log="Application" machineName="." traceOutputOptions="None" />
- </listeners>
- <formatters>
- <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
- template="Timestamp: {timestamp(local)}{newline}
- Message: {message}{newline}
- Category: {category}{newline}
- Priority: {priority}{newline}
- Severity: {severity}"
- name="Text Formatter" />
- </formatters>
- <categorySources>
- <add switchValue="All" autoFlush="true" name="General">
- <listeners>
- <add name="Rolling Flat File Trace Listener" />
- <add name="Event Log Trace Listener" />
- </listeners>
- </add>
- </categorySources>
- <specialSources>
- <allEvents switchValue="All" name="All Events">
- <listeners>
- <add name="Rolling Flat File Trace Listener" />
- </listeners>
- </allEvents>
- <notProcessed switchValue="All" name="Unprocessed Category">
- <listeners>
- <add name="Rolling Flat File Trace Listener" />
- </listeners>
- </notProcessed>
- <errors switchValue="All" name="Logging Errors & Warnings">
- <listeners>
- <add name="Rolling Flat File Trace Listener" />
- </listeners>
- </errors>
- </specialSources>
- </loggingConfiguration>
Now, the configuration part is done for the Logging block which can be used throughout the application level.
Let’s build a sample Console application to log some messages.
LoggerBlock Class
- using Microsoft.Practices.EnterpriseLibrary.Logging;
-
- namespace LoggingApplicationBlock
- {
- public class LoggerBlock
- {
- protected LogWriter logWriter;
-
- public LoggerBlock()
- {
- InitLogging();
- }
-
- private void InitLogging()
- {
- logWriter = new LogWriterFactory().Create();
- Logger.SetLogWriter(logWriter, false);
- }
-
- public LogWriter LogWriter
- {
- get
- {
- return logWriter;
- }
- }
- }
- }
Executer Class
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Text;
-
- namespace LoggingApplicationBlock
- {
- class Executer
- {
- LoggerBlock loggerBlock = new LoggerBlock();
-
- public static void Main()
- {
- new Executer().ReadFile();
- }
-
- public void ReadFile()
- {
- WriteTraceLog("Application Started!!!");
-
- string[] lines;
- var list = new List<string>();
- var fileStream = new FileStream(@"sample.txt", FileMode.Open, FileAccess.Read);
- using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
- {
- string line;
- while ((line = streamReader.ReadLine()) != null)
- {
- WriteTraceLog(line);
-
- list.Add(line);
- }
- }
-
- lines = list.ToArray();
-
- WriteTraceLog("Application Stopped!!!");
- }
-
- public void WriteTraceLog(String message)
- {
- loggerBlock.LogWriter.Write(message, "General", 5, 2000, TraceEventType.Information);
- }
- }
- }
Once you execute the application, it will create the Log file in the debug folder as I have not mentioned any specific path for the file in the configuration.
You can see here, the messages are logged as per the template format.
Also, you can see that the same messages have been logged in the Windows event log too.
Resources
Conclusion
The best part of Logging Application Block is that you can change log template format, roll interval and log file path on the fly without compiling the code. You can also change the error logging source from event viewer to file or email. I have attached the sample application. Just download it and experience the Logging Application Block functionality in Microsoft Enterprise Library 6.0.
I hope you have enjoyed this article and I am sure if you use this block properly, you can have a very stable, efficient, and flexible logging framework.
In the next article, we will cover Exception Handling Application Block in Microsoft Enterprise Library 6.0.
Happy Coding!!!