Our today discussion is about logging in .NET apps. In this demonstration I will use Visual Studio 2005 and Enterprise Library 3.1 - May 2007.
The Microsoft Enterprise Library is a set of tools and programming libraries for the Microsoft .NET Framework. Enterprise Library Logging Application Block provides you tool for perform logging into your application easily.
All you need is this using directive:
using Microsoft.Practices.EnterpriseLibrary.Logging;
and reference to: “Microsoft.Practices.EnterpriseLibrary.Logging“.
And when you want to log some method, you do it like this:
LogEntry log = new LogEntry();
log.Priority = 1;
log.Message = "Executing";
log.Categories.Add("General");
log.Title = "Executing method name";
Logger.Write(log);
that is all you need to put into your code. Take a look this line: “log.Categories.Add(”General”);”.
At this moment developer doesn’t know how application perform the logging. Does it use some txt file, database or something else. That is why we use App.config file to specify things like that. For editing App.config I suggest to do this edit tool: right click on App.config and select “Edit Enterpise Library Confoguration” .

When we want to use logging, 1-st we have to add “Category”. Take a look at picture!

I will call my Category “General”. Category gets name by Default, so you use “Property” window to change it’s name. After that add trace reference to your category.

For trace reference we need trace listener! So let’s add some trace listener, like this:

I selected “Flat File Trace Listener“. Choose Property for your trace listener. I select Filename to be: C:\trace.log.

After that select “Trace Reference Listener” and in it’s property window connect it to FlatFileTraceListener. Like this:

And that would be all. Now start your application and take a look at file: C:\trace.log.
We can go one step further and create our Logging class. Here is how can we do that.
Create new project in your solution, and call it Logger, type of project: Class Library, language C#. You have to add reference to you project for: “Microsoft.Practices.EnterpriseLibrary.Logging“.
and here is your class:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Logging;
namespace Logger
{
public static class MyLogger
{
public static void Logg(String message, String category, Int32 priority, String title)
{
LogEntry log = new LogEntry();
log.Priority = priority;
log.Message = message;
log.Categories.Add(category);
log.Title = title;
Logger.Write(log);
}
}
}
and here is how you call it from some of your method. First add reference to Logger project.
Logger.MyLogger.Logg("Exucuting method name", "General", 1, "before method start");
Leave a Reply
You must be logged in to post a comment.
Recent Comments