Logging Application Block In Microsoft Enterprise Library 6.0


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 the application blocks?

The definition we use is “pluggable and reusable software compo­nents 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.
We have to install Enterprise Library – Logging Application Block from NuGet Packages.
Once it is installed successfully, the 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 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 a 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.
  1. <configSections>  
  2.      <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />  
  3. </configSections>  
  4. <loggingConfiguration name="" tracingEnabled="false" defaultCategory="General" logWarningsWhenNoCategoriesMatch="false">  
  5.      <listeners>  
  6.           <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" fileName="RollingFlatFile.log" footer="----------------------------------" formatter="Text Formatter" header="" rollInterval="Day" traceOutputOptions="DateTime, Timestamp" filter="All" />  
  7.           <add name="Event Log Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" source="Application" formatter="Text Formatter" log="Application" machineName="." traceOutputOptions="None" />  
  8.      </listeners>  
  9.      <formatters>  
  10.           <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" template="Timestamp: {timestamp(local)}{newline}    
  11.     Message: {message}{newline}    
  12.     Category: {category}{newline}    
  13.     Priority: {priority}{newline}    
  14.     Severity: {severity}" name="Text Formatter" />  
  15.      </formatters>  
  16.      <categorySources>  
  17.           <add switchValue="All" autoFlush="true" name="General">  
  18.                <listeners>  
  19.                     <add name="Rolling Flat File Trace Listener" />  
  20.                     <add name="Event Log Trace Listener" />  
  21.                </listeners>  
  22.           </add>  
  23.      </categorySources>  
  24.      <specialSources>  
  25.           <allEvents switchValue="All" name="All Events">  
  26.                <listeners>  
  27.                     <add name="Rolling Flat File Trace Listener" />  
  28.                </listeners>  
  29.           </allEvents>  
  30.           <notProcessed switchValue="All" name="Unprocessed Category">  
  31.                <listeners>  
  32.                     <add name="Rolling Flat File Trace Listener" />  
  33.                </listeners>  
  34.           </notProcessed>  
  35.           <errors switchValue="All" name="Logging Errors & Warnings">  
  36.                <listeners>  
  37.                     <add name="Rolling Flat File Trace Listener" />  
  38.                </listeners>  
  39.           </errors>  
  40.      </specialSources>  
  41. </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

    1. using Microsoft.Practices.EnterpriseLibrary.Logging;  
    3. namespace LoggingApplicationBlock {  
    4.     public class LoggerBlock {  
    5.         protected LogWriter logWriter;  
    7.         public LoggerBlock() {  
    8.             InitLogging();  
    9.         }  
    11.         private void InitLogging() {  
    12.             logWriter = new LogWriterFactory().Create();  
    13.             Logger.SetLogWriter(logWriter, false);  
    14.         }  
    16.         public LogWriter LogWriter {  
    17.             get {  
    18.                 return logWriter;  
    19.             }  
    20.         }  
    21.     }  

      Executer Class

      1. using System;  
      2. using System.Collections.Generic;  
      3. using System.Diagnostics;  
      4. using System.IO;  
      5. using System.Text;  
      7. namespace LoggingApplicationBlock {  
      8.     class Executer {  
      9.         LoggerBlock loggerBlock = new LoggerBlock();  
      11.         public static void Main() {  
      12.             new Executer().ReadFile();  
      13.         }  
      15.         public void ReadFile() {  
      16.             WriteTraceLog("Application Started!!!");  
      18.             string[] lines;  
      19.             var list = new List < string > ();  
      20.             var fileStream = new FileStream(@ "sample.txt", FileMode.Open, FileAccess.Read);  
      21.             using(var streamReader = new StreamReader(fileStream, Encoding.UTF8)) {  
      22.                 string line;  
      23.                 while ((line = streamReader.ReadLine()) != null) {  
      24.                     WriteTraceLog(line);  
      26.                     list.Add(line);  
      27.                 }  
      28.             }  
      30.             lines = list.ToArray();  
      32.             WriteTraceLog("Application Stopped!!!");  
      33.         }  
      35.         public void WriteTraceLog(String message) {  
      36.             loggerBlock.LogWriter.Write(message, "General", 5, 2000, TraceEventType.Information);  
      37.         }  
      38.     }  

        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.


        The best part of the 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 the 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!!!