Saturday, January 8, 2011

Logging using Enterprise Library... How simple is that?

I am sure you will agree with me how much a logging class is useful to help you isolate that problem. Especially when you are going through a lot of workflows which to simulate and debug becomes a nightmare.



Every project will require some kind of logging either you just want to see if your calls are made as expected OR if you want to take special actions like sending a mail based on the criticality of the log entry.

How long do you think it is going to take to do the following:


Add a class LogginManager.cs


using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Diagnostics;



public static class LoggingManager

{
    public static void Write(string message, TraceEventType eventType)
    {
        if (Logger.IsLoggingEnabled())
        {
            LogEntry entry = new LogEntry
           {
                 Message = message,
                 Severity = eventType
            };
       
            Logger.Write(entry);
        }
    }
}


Add the following libraries in GAC
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Interception.dll

Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.EnterpriseLibrary.Logging.dll
Microsoft.Practices.EnterpriseLibrary.Common.dll


Now start using Logging class,
LoggingHandler.Write(ex.Message, System.Diagnostics.TraceEventType.Critical);



There is a tool to configure your web/app.config. Follow these basic steps to get you going.



To configure:


1. Open the web.config/app.config from the Enterprise Library Configuration tool. There is also a Visual Studio Add-in to configure directly from Visual Studio.
2. Blocks > Add Logging Settings
3. Add a Logging Target Listener > Add Flat File Trace Listener – Change its formatter to Text Formatter.
4. Change the Listener for the General Category to Flat File Trace Listener
5. Change the Listener for the Logging Errors & Warnings to Flat File Trace Listener
6. Add a Logging Filter > Logging Enabled Filter. Set All Logging to true
7. Save and you are good to go.


You should be able to see the logs in a file called Trace.log under your bin directory. You can change what you see as part of the Logs by modifying the Text Formatter contents.


Recommend using this for logging, there are lot more to offer from the Enterprise Library. Go through,

http://entlib.codeplex.com/wikipage?title=EntLib5&referringTitle=Home


No comments:

Post a Comment