Logging Application Block

How to use Logging Application Block in Enterprise Library to log the information

Logging the errors, exceptions and other information is a common thing in software development. In .NET environment we can easily use Microsoft Enterprise Library Logging Application Block to log any information in web applications or desktop applications. This application component is very useful and coming in a handy way to configure. Logging Application Block allows us to decouple the logging functionality from our application code. There is a tool available for the configuration setup. To get a basic knowledge please read the documentation from Microsoft.

My requirement is to log my custom messages in the application to a log file. It should be automatically roll after a pre-defined size.

Here I’m creating a sample project and adding the  Logging Application Block using the Nuget package manager.

nuget logging application block

After installing this we can use the Enterprise library configuration tool to configure the logging in our application. This feature is available when you go to the web.config file in your application and when you open the web.config file, you can see the “Edit server configuration ” option under tools menu. Under Blocks menu item we have the option to add a Logging Setting.

I have added a logging setting to log the application information.

  1. Add some categories like “Error”, “Info”, “Warning”
  2. Add a listener to the logging setting. Here I used “Rolling Flat File Trace Listener” based on my requirements.
application console
application console. Click on image to ZOOM

This will add a new section to the web.config file.

web config changes
web config changes

different kind of listeners are available and all of them have different purposes.

3. I added a new class to log my information  and I’m passing the messages to the Logging Application Block through my class.

 

 public enum LogPriority
    {

Low = 0, 

Medium = 3, 
High = 5 
} 

public class Log : IDisposable
    {
        public void Dispose()
        {
            
        }

        public void Add(string logMessage, string category, LogPriority priority)
        {
            //Check if the logMessage or category is empty. 
            if (logMessage == string.Empty || category == string.Empty)
                return;

            LogEntry entry = new LogEntry();
            entry.Message = logMessage;
            entry.Priority = (int)priority;
            entry.Categories.Add(category);

            IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
            LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
            Logger.SetLogWriter(logWriterFactory.Create(), false);

            Logger.Write(entry);
        }
    }

How to add logs to the Logging Application Block

4. In the controller action I have added my sample message to the Logging Application Block.

 

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Log logger = new Log();

            logger.Add("Index action", "Info", LogPriority.Low);
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }

This will add a log entry in the log file under “Info” category something like below.
—————————————-
Timestamp: 7/25/2017 7:03:08 AM

Message: Index action

Category: Info

Priority: 0

Extended Properties:
—————————————-

Customize message formats in Logging Application Block

This message format can be configured using the Text formatters. We can add custom fields to the message using Extended properties.

Ex:

Dictionary<string, object> extendedProperties = new Dictionary<string,object>();
Var userId = this.UserId; // Logged in user Id
extendedProperties.Add("User", userId);

Logger.Write(logMessage, category, extendedProperties);

Output


Message: Index action

Category: Info

Priority: 0

User: user 01
—————————————-

Sajith Dilhan on FacebookSajith Dilhan on Linkedin
Sajith Dilhan
Software Developer at Sana Commerce

Leave a Reply

Your email address will not be published. Required fields are marked *