20 Jan

Enterprise Library Logging 101

Category:General PostTag: :

This article demonstrates the absolute minimum effort necessary to begin logging messages from within your application using Microsoft?s Enterprise Library 4.1.

I will include only a few details about what is happening under the covers, this is simply a HOW TO for getting that first logging message out there from a C# code file.

Installing Enterprise Library

Download and install the Enterprise Library 4.1.  Realize that you are getting and installing a lot more than a logging library here. Be patient.

Creating a new Visual Studio project

  1. Open Visual Studio.
  2. Select New | Project | Visual C# | Console Application
  3. Name the project something appropriate like HelloWorldEntLibLogging

Adding a reference to the Ent. Lib. logging assembly

  1. In Solution Explorer, right click the project node and select Add Reference.
  2. On the .NET tab, select Enterprise Library Logging Application Block
    as shown
  3. Click OK.

Configure Logging for the Application

Much of EntLib?s functionality is specified through configuration. Logging is no exception. Here, you?ll add an application configuration file to the project and add configuration information to it with the Visual Studio add-in that the EntLib installer added to Visual Studio.

  1. In Solution Explorer, right click the project node and select Add | New Item.
  2. Select Visual C# Items | General | Application Configuration File
  3. Leave the filename App.config as shown
  4. Click Add
  5. Open app.config in the XML editor (double click it in Solution Explorer) and note that it is empty. You should see something like this:
       1: <?xml version="1.0" encoding="utf-8"?>
       2: <configuration>
       3: </configuration>

  6. Close app.config.
  7. Right click app.config in Solution Explorer and select Edit Enterprise Library Configuration as shown:


    The Enterprise Library Configuration Editor opens.

  8. Right click the app.config node in the editor and select New | Logging Application Block as shown:


    A new Logging Application Block node is added to the configuration editor as shown:


  9. Close the app.config visual editor window.
  10. Double click app.config in Solution Explorer to open it in the XML editor. You can see the configuration XML added for the logging block.
       1: <?xml version="1.0" encoding="utf-8"?>
       2: <configuration>
       3:     <configSections>
       4:         <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
       5:         <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
       6:     </configSections>
       7:     <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
       8:         defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
       9:         <listeners>
      10:             <add source="Enterprise Library Logging" formatter="Text Formatter"
      11:                 log="Application" machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
      12:                 traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
      13:                 name="Formatted EventLog TraceListener" />
      14:         </listeners>
      15:         <formatters>
      16:             <add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}&#xD;&#xA;Category: {category}&#xD;&#xA;Priority: {priority}&#xD;&#xA;EventId: {eventid}&#xD;&#xA;Severity: {severity}&#xD;&#xA;Title:{title}&#xD;&#xA;Machine: {machine}&#xD;&#xA;Application Domain: {appDomain}&#xD;&#xA;Process Id: {processId}&#xD;&#xA;Process Name: {processName}&#xD;&#xA;Win32 Thread Id: {win32ThreadId}&#xD;&#xA;Thread Name: {threadName}&#xD;&#xA;Extended Properties: {dictionary({key} - {value}&#xD;&#xA;)}"
      17:                 type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
      18:                 name="Text Formatter" />
      19:         </formatters>
      20:         <categorySources>
      21:             <add switchValue="All" name="General">
      22:                 <listeners>
      23:                     <add name="Formatted EventLog TraceListener" />
      24:                 </listeners>
      25:             </add>
      26:         </categorySources>
      27:         <specialSources>
      28:             <allEvents switchValue="All" name="All Events" />
      29:             <notProcessed switchValue="All" name="Unprocessed Category" />
      30:             <errors switchValue="All" name="Logging Errors &amp; Warnings">
      31:                 <listeners>
      32:                     <add name="Formatted EventLog TraceListener" />
      33:                 </listeners>
      34:             </errors>
      35:         </specialSources>
      36:     </loggingConfiguration>
      37: </configuration>

    This can look intimidating the first time you see it. There is a lot of XML in there and that stays pretty true to the idea that with flexibility comes complexity. Ignore all this for now and just close the XML editor window.

      Adding Logging Code to the Application

      OK, the application is all configured up to work with logging and the dependencies are linked in. Time to code.

      1. Open Program.cs in the code editor.
      2. Add the highlighted using statement at the top of the code file.
      3. using Microsoft.Practices.EnterpriseLibrary.Logging;

      4. Inside the Main method, instantiate a new LogEntry object and set its Message property to something appropriate, like ?Hello EntLib Logging?.
      5. Use the static Logger.Write() method to submit the LogEntry for logging.

      Your code should look similar to this:

      class Program
          static void Main(string[] args)
              LogEntry entry = new LogEntry()
                                       Message = "Hello Ent. Lib. Logging"

      You?ve done it! Your very first EntLib logging application.

      Running the Application and Validating the Logging

      1. Press  F5.

        The application runs under the debugger and exits quickly, just flashing a command window.
      2. Open the Windows Event Viewer.

        I am running on Windows 2008 Server, so I just Start ?Event Viewer?

      3. Open the application event log and view recent events.

      You should see an informational event logged to the Windows Event Log as shown below.


      The details of the information logged will look much like this:

      Timestamp: 1/20/2009 11:20:08 PM

      Message: Hello Ent. Lib. Logging

      Category: General

      Priority: -1

      EventId: 0

      Severity: Information


      Machine: BIGRED

      Application Domain: HelloEntLibLogging.vshost.exe

      Process Id: 5384

      Process Name: C:\projects\sandbox\HelloEntLibLogging\HelloEntLibLogging\bin\Debug\HelloEntLibLogging.vshost.exe

      Win32 Thread Id: 4512

      Thread Name:

      Extended Properties:

      Although you can greatly control and extend the information logged here, we?ll save that for another time. For a simple ?gee whiz? try this.

      Up the severity of you LogEntry when it is instantiated like this:

      LogEntry entry = new LogEntry()
                               Message = "Hello Ent. Lib. Logging",
                               Severity = TraceEventType.Critical

      Now when you run the app, you get a really bad log entry :).



      9 thoughts on “Enterprise Library Logging 101

      1. Nice summary. I’ve been trying to fight the “Entlib’s too complicated” meme for a while now, and stuff like this really helps.

        Having said this, I’d like to mention that this is, in fact, NOT the bare minimum code. Instead of creating a separate LogEntry object you can just do:

        Logger.Write(“See, even simpler!”);

        There are a bunch of overloads on Logger to do severity, categories, etc. without requiring an explicit LogEntry.

      2. Hey david , Gr88 post ! 

        Secondly could you just help out with writing the LogWriter to write in an xml file or a text file ? 

      Comments are closed.