How To Configure and Use the Logging Application Block

by praveen 1/5/2009 8:58:05 AM

I recently downloaded the Enterprise Library 4.1 released in October 2008. I guess the enterprise library has done a lot of improvements from the 3.x version to the current 4.x that's available and not just making it work with .NET Framework 3.5 and integration with WCF.

I downloaded the library and as all bad developers do, immediately started looking into the Quick Start code sample and trying to figure out, how to get it quickly integrated with my application. Whatever happened to doing research and reading through the documentation, that I keep preaching to other people? Guess I threw that all out of the window :-) So in this process of going all over the place without really reading anything, cost me a day and that too when we are in the middle of a high priority project, where every single day is crucial. So I went back and spent some time patiently reading through the documentation available on MSDN. Although the documentation is great, it doesn't really give a step-by-step walkthrough for someone who just wants to reuse the Enterprise Library Logging Block and not customize it. So.. I will jump straight into it.

 

Defining the Requirements

First, lets talk about my requirements. So here is what I wanted to do. While looking at logging, following are some thing we wanted to log.

  1. Whenever an exception occurs, log it to event logs. Exception can have different severity levels (Critical, Error, Warning, Information etc).
  2. We will have our own Event Log Name (lets call it DotNetScraps) and event log source (lets call it MyWindowsApp)
  3. We should be able to also log the exception to a text file, which is easier to share etc.
  4. More debug logging should be allowed to the text file, so when in production environment, we should be able to debug through the code by looking at the text file.
  5. Tracing is also required, so we can figure out which method took how much time to complete.

 

Now that we have the requirements defined, lets move on to see how we can use the Logging Application Block to help us meet these requirements.

 

Step 1 -- Setting up the Environment

The first thing you will of course need to do is download and install the Enterprise Library 4.1. When you install this don't bother to launch the source code installer, you can always do that if you want to later. As we are only planning to reuse whatever the PnP team is giving us out-of-the-box, we don't need to worry about this bit.

Enterprise Library 4.1 comes with all the assemblies already compiled and ready for use. The default path for these assemblies is C:\Program Files\Microsoft Enterprise Library 4.1 - October 2008\Bin, if you are in a 64-bit environment, you can check the Program Files(x86) for the same path. All the assemblies located in here are already strong named. To meet our requirements we only need the following assemblies.

  • Microsoft.Practices.EnterpriseLibrary.Common.dll
  • Microsoft.Practices.EnterpriseLibrary.Logging.dll
  • Microsoft.Practices.ObjectBuilder2.dll

You can put these assemblies in GAC as they are already strong named with the Microsoft private key.

 

One of the requirements we had was to write to event logs. Now for doing this we will need to write some code, find below a code for a console application that creates the event log and event source.

using System;
using System.Diagnostics;
 
namespace CreateEventSource
{
    class Program
    {
        const string __eventLogName = "DotNetScraps";
        const string __eventLogSource = "MyWindowsApp";
 
        static void Main(string[] args)
        {
            if (!EventLog.SourceExists(__eventLogSource))
            {
                EventLog.CreateEventSource(__eventLogSource, __eventLogName);
            }
            Console.WriteLine("Event Log and source created");
        }
    }
}

 

You can change the constant values defined at the top to define your own event log name and source. One thing to note here is that if the Event Log doesn't exist it gets created automatically.

 

Step 2 -- Configuring your applications config file

Once you have all those things setup, first go ahead and add references to the assemblies you had GAC'd in Step 1 to your application. I am picking up a windows console application as an example. Also make sure you have a config file added to the project. Once the references are added. Go to Start--> All Programs --> Microsoft Patterns and Practices--> Enterprise Library 4.1 - October 2008 and open up the "Enterprise Library Configuration"

In the configuration tool then hit the File-->Open Application and browse and open the config file of your application. Enterprise Library by default adds the "Data Access Application Block". You can right click on this and say "Remove" unless you are planning to have it also in your code.

Then right click on the config file path and then say New-->Logging Application Block. When you add the logging application block, it will add a Text Formatter and a Formatted EventLog TraceListener. This Event Log Trace Listener is then added to a general configuration and also to Special Sources.  Lets get rid of all of these, we will add them again so you will understand how these work together. When you remove all the default stuff... your tool will look like the following screenshot.

 

image

 

Before we go in further here is a brief description of the different sections, if you need more details please refer to the MSDN Documentation for the Logging Application Block.

 

Property Description
Filters All log entries are passed through filters, you can use them to block the logging based on a category or priority etc. We won't be using this for our example.
Category Sources You can have your own category definition or use the ones provided by default like Logging Errors & Warnings, Unprocessed category or All Events.
Trace Listeners This is the main guy who does the listening and you can define the Trace Listener of your choice. Since we are writing to event logs and text, we will use the "Formatted Event Log Trace Listener" and the "Rolling Flat File Trace Listener"
Formatters These define the kind of formatting you need for your log entry, you get to choose between Binary, Custom and Text. We will use the Text formatter.

 

First thing we will do is setup the Formatter. So, right click the Formatter and add a "Text Formatter". Rename it appropriately and change the template. This template is the format your log entry will be created in. You can modify this as per your choice.

Next step would be to add the Event Log Listener, so you can write to event logs. Right click the Trace Listeners and choose "Formatted EventLog TraceListener". Update the name, leave the Filter set to "All", update the Formatter to point to the text formatter you created before. Change the Log name to "DotNetScraps" (if that's what you have created, or whatever custom Log you have) and the Source to "MyWindowsApp" (if you have followed the sample above or whatever name you gave). Here is a screen shot of how this will look.

 

image

 

Next, Add a Category to the "Category Sources". Right click the Category Sources and choose New-->Category. Rename it appropriately and then right click the category you have created and choose New-->Trace Listener Reference. When this added update the ReferenceTraceListener to choose the Trace Listener that you had created.

Now you are all set with the Configuration to write to event logs, lets move on to Debug Log.

For having a debug log lets keep the Text Formatter we created. Add a Trace Listener and choose a "Rolling Flat File Trace Listener". A rolling file listener is a bit different from the standard "Flat File Trace Listener". The former offers additional functionality so that a new text file is created automatically based on a Time Interval or size of the file or both, you can also choose to overwrite the existing file rather than create new file at every interval. It is quite useful as this way you don't have to deal with huge text files later which are difficult to open. In my example I have renamed this to DebugFileListener.

One thing we need to take care of here is to have an appropriate path in the "FileName" for the listener, this is the path where the log file will be stored. Also choose the formatter as your existing formatter that you had created.

Next would be to add a category (lets call it DebugFileCategory) and add the DebugFileListener to this.You are now done with the configuration for Debug Logging.

Coming to the last step, we are going to have Tracing enabled so we can Trace methods. For doing this, first add a new Text Formatter lets call it TraceFormatter. Change the template for this to have only TimeStamp and Message as that is all that we need. Next, add a "Rolling File Trace Listener", call it TraceListener and change the formatter to point to the TraceFormatter and adjust the other settings as per your need.

Then add a Category and call it "Trace" and to this category add a listener and point this to the "TraceListener" we just created. This should configure your Tracing now.

You are now all done with the configuration and here is is a screenshot of how this will look once everything is configured correctly.

 

image

 

Step 3 -- Code Sample to write to Event Logs, Debug and Tracing

Writing code now is easy, you can use a logEntry class to create your log or directly call the logger.Write method to write to log, find below a complete listing of my sample code which demonstrates this.

using System;
using System.Diagnostics;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Logging;
 
 
namespace MyLoggerTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (new Tracer("Trace"))
            {
                LogEntry _logentry = new LogEntry();
                _logentry.Categories.Add("EventLogCategory");
                _logentry.Priority = 2;
                _logentry.EventId = 4000;
                _logentry.Severity = TraceEventType.Information;
                _logentry.Title = "My Title";
                _logentry.Message = "Message from Log Entry Object";
                Logger.Write(_logentry);
 
 
                Logger.Write("This is being written to text file", "DebugCategory", 2, 2000, TraceEventType.Information, "My method");
 
                Console.WriteLine("Logs Written...");
            }
        }
    }
}

 

If you review the code above we are having a statement like

using (new Tracer("Trace"))

This piece of code is the one doing the tracing, the constructor for this object will trace the start time to the trace log and when the object gets disposed it will write the end time. Here is an example of how my log looks like when I run the code.

----------------------------------------
Timestamp: 1/5/2009 2:59:49 AM
Message: Start Trace: Activity '551c5f0f-3bf0-4f58-82dd-73a4e59acbd8' in method 'MyLoggerTest.Program.Main' at 6500379828285 ticks

----------------------------------------
----------------------------------------
Timestamp: 1/5/2009 2:59:49 AM
Message: Message from Log Entry Object

----------------------------------------
----------------------------------------
Timestamp: 1/5/2009 2:59:49 AM
Message: This is being written to text file

----------------------------------------
----------------------------------------
Timestamp: 1/5/2009 2:59:49 AM
Message: End Trace: Activity '551c5f0f-3bf0-4f58-82dd-73a4e59acbd8' in method 'MyLoggerTest.Program.Main' at 6500697765480 ticks (elapsed time: 0.105 seconds)

----------------------------------------

 

Also, the first log entry code that we wrote, is writing to event logs and this is how it looks.

 

image

 

And here is how the log to Text file looks like

----------------------------------------
Timestamp: 1/5/2009 3:03:41 AM
Category: DebugCategory, Trace
Priority: 2
EventId: 2000
Severity: Information
Title:My method
Machine: <<MYMACHINENAME>>
Application Domain: MyLoggerTest.exe
Process Id: 2288
Process Name: D:\projects\MyLoggerTest\MyLoggerTest\bin\Release\MyLoggerTest.exe
Message: This is being written to text file
----------------------------------------

 

Step 4 -- Reviewing the application config file 

If you open up the application's config file, there is an entire section added called "loggingConfiguration" and its called "Logging Application Block". Also if you review it, you will see all the listeners, formatters and configuration sections added in there. Lets take a closer look at the category sources section.

<categorySources>
      <
add switchValue="All" name="Trace">
        <
listeners>
          <
add name="TraceListener" />
        </
listeners>
      </
add>
      <
add switchValue="All" name="DebugCategory">
        <
listeners>
          <
add name="DebugFileListener" />
        </
listeners>
      </
add>
      <
add switchValue="All" name="EventLogCategory">
        <
listeners>
          <
add name="MyAppEventLogListener" />
        </
listeners>
      </
add>
      <
add switchValue="All" name="General" />
    </
categorySources>

 

If you notice the switchValue in there its set to "All", you can toggle this to various levels or just say "Off" and it will stop logging to the particular category. This is useful when you want to move the code to production environment and disable the debug logging or trace logging.

 

Step 5 -- Deploying to another Environment

If we want to deploy to production or even a staging environment here are the steps we will need to take.

  1. First copy the assemblies mentioned in Step 1 mentioned above, these will need to be added to the GAC on the target machine.
  2. Next copy your application and its config file to the target machine at the desired location.
  3. Create the Event Log and Event source on the target machine.
  4. Edit the Configuration file to change the path to the Trace Log and the Debug file log.
  5. Toggle the switch for Debug Category or Trace Category if you don't want to log that in target machine.

 

And that's all for now Folks!!!

Tags: , , ,

.NET | C# | Microsoft | Tips and Tricks | Enterprise Library

blog comments powered by Disqus

Comments


Who is Rahul?

Rahul

He works for Microsoft and likes Software & Gadgets!

He shares some interesting notes here while working with stuff that excites him.

Disclaimer

The opinions expressed herein are our own personal opinions and do not represent our employer's view in any way.
© Copyright 2014, Rahul Soni