January 17, 2014

Enterprise Library 6 Changes - Exception Handling and Logging Application blocks configuration

I was developing a framework services project for my new assignment .. (getting hands dirty after a while .. :) ).. Seems that there is a change in the way we configure our helper classes to log and handle  exception

For Logging:

common approach to create a log entry using the following code-

LogEntry entry = new LogEntry();
entry.Message = "I am logging";
Logger.Write(entry);

 works fine with Enterprise Library 5.0. But in 6.0 it gives the error "The LogWriter has not been set for the Logger static class. Set it invoking the Logger.SetLogWriter method" 

Following snippet will fix the issue

IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
Logger.SetLogWriter(logWriterFactory.Create());
LogEntry entry = new LogEntry();
entry.Message = "I am logging";
Logger.Write(entry)


For Exception Handling

 public static bool HandleException(Exception exceptionToHandle)
        {
            IConfigurationSource config = ConfigurationSourceFactory.Create();
            ExceptionPolicyFactory factory = new ExceptionPolicyFactory(config);
            ExceptionPolicy.SetExceptionManager(factory.CreateManager());
            return ExceptionPolicy.HandleException(exceptionToHandle, 
                "Policy");            
        }

Don't forget to add reference to "System.Configuration" assembly to your project, else you will get error and add it in the "using" list.