Dec 15 2009

Add Log4net .dll to your projects for easy logging and optimal error handling

Category: ASP.NETryancmartin1976 @ 20:55

First Strategy:

Second Strategy:

Building your own logging framework can be time consuming and a waste of time because log4net already did it for you.

STEP 1

Download the dll and config from there site: http://logging.apache.org/log4net/download.html

STEP 2

Drop the dll and the config file into your bin directory and add a reference to the dll from Visual Studio project.

STEP 3

Add a Log directory under your root directory

STEP 4

Add this code, preferably to your Data Access or Service layer and name it Log.cs:

using System;
using System.Collections.Generic;
using System.IO;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Layout;
 
public static class Log
{
    private static Dictionary<Type, ILog> _loggers = new Dictionary<Type, ILog>();
    private static bool _logInitialized = false;
    private static object _lock = new object();
 
    public static string SerializeException(Exception e)
    {
        return SerializeException(e, string.Empty);
    }
 
    private static string SerializeException(Exception e, string exceptionMessage)
    {
        if (e == null) return string.Empty;
 
        exceptionMessage = string.Format(
            "{0}{1}{2}\n{3}",
            exceptionMessage,
            (exceptionMessage == string.Empty) ? string.Empty : "\n\n",
            e.Message,
            e.StackTrace);
 
        if (e.InnerException != null)
            exceptionMessage = SerializeException(e.InnerException, exceptionMessage);
 
        return exceptionMessage;
    }
 
    private static ILog getLogger(Type source)
    {
        lock (_lock)
        {
            if (_loggers.ContainsKey(source))
            {
                return _loggers[source];
            }
 
            ILog logger = LogManager.GetLogger(source);
            _loggers.Add(source, logger);
            return logger;
        }
    }
 
    public static void Debug(object source, object message)
    {
        Debug(source.GetType(), message);
    }
 
    public static void Debug(Type source, object message)
    {
        getLogger(source).Debug(message);
    }
 
    public static void Info(object source, object message)
    {
        Info(source.GetType(), message);
    }
 
    public static void Info(Type source, object message)
    {
        getLogger(source).Info(message);
    }
 
    public static void Warn(object source, object message)
    {
        Warn(source.GetType(), message);
    }
 
    public static void Warn(Type source, object message)
    {
        getLogger(source).Warn(message);
    }
 
    public static void Error(object source, object message)
    {
        Error(source.GetType(), message);
    }
 
    public static void Error(Type source, object message)
    {
        getLogger(source).Error(message);
    }
 
    public static void Fatal(object source, object message)
    {
        Fatal(source.GetType(), message);
    }
 
    public static void Fatal(Type source, object message)
    {
        getLogger(source).Fatal(message);
    }
 
    public static void Debug(object source, object message, Exception exception)
    {
        Debug(source.GetType(), message, exception);
    }
 
    public static void Debug(Type source, object message, Exception exception)
    {
        getLogger(source).Debug(message, exception);
    }
 
    public static void Info(object source, object message, Exception exception)
    {
        Info(source.GetType(), message, exception);
    }
 
    public static void Info(Type source, object message, Exception exception)
    {
        getLogger(source).Info(message, exception);
    }
 
    public static void Warn(object source, object message, Exception exception)
    {
        Warn(source.GetType(), message, exception);
    }
 
    public static void Warn(Type source, object message, Exception exception)
    {
        getLogger(source).Warn(message, exception);
    }
 
    public static void Error(object source, object message, Exception exception)
    {
        Error(source.GetType(), message, exception);
    }
 
    public static void Error(Type source, object message, Exception exception)
    {
        getLogger(source).Error(message, exception);
    }
 
    public static void Fatal(object source, object message, Exception exception)
    {
        Fatal(source.GetType(), message, exception);
    }
 
    public static void Fatal(Type source, object message, Exception exception)
    {
        getLogger(source).Fatal(message, exception);
    }
 
    private static void initialize()
    {
        string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log4Net.config");
        if (!File.Exists(logFilePath))
            logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"bin\Log4Net.config");
 
        XmlConfigurator.ConfigureAndWatch(new FileInfo(logFilePath));
    }
 
    public static void EnsureInitialized()
    {
        if (!_logInitialized)
        {
            initialize();
            _logInitialized = true;
        }
    }
}

STEP 5

Add a global.asax file and add this code to it

protected void Application_Start(object sender, EventArgs e)
        {
            Log.EnsureInitialized();
        }

STEP 6

Invoke an error and log it!

public string GetTestDataAndValidate()
        {
            try
            {
                string returnData = testRepository.GetData();
                if (string.IsNullOrEmpty(returnData))
                    Log.Warn(this, "there should be data coming back");
                else if (returnData.Contains("error"))
                    Log.Error(this, returnData);
                return returnData;
            }
            catch (Exception ex)
            {
                Log.Fatal(this, ex.InnerException);
                return "";
            }
        }

STEP 7

That's it! Done! Go see the error log results for yourself. If everything was configured correctly you should have an error log in your Logs directory under the root directory in your web application.

You should play around with the Log4Net.config file until you get the results your looking for.

<?xml version="1.0" encoding="utf-8"?>
<log4net debug="false">
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="Logs/log.xml" />
    <appendToFile value="true" />
    <datePattern value="yyyyMMdd" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="1000KB" />
    <layout type="log4net.Layout.XmlLayoutSchemaLog4j">
      <locationInfo value="true" />
    </layout>
  </appender>
  <root>
    <level value="DEBUG" />
    <appender-ref ref="RollingFileAppender" />
  </root>
  <logger name="StructureMap" additivity="false">
    <level value="WARN"/>
    <appender-ref ref="OutputDebugStringAppender" />
    <appender-ref ref="ConsoleAppender" />
  </logger>
  <logger name="NHibernate" additivity="false">
    <level value="INFO"/>
    <appender-ref ref="AspNetTraceAppender" />
  </logger>
</log4net>

Tags: , , , , ,