Configure Log4Net in Code

by jasonvonruden 28. November 2012 15:39

One of the most annoying things when trying to debug Log4Net logging problems is trying to get the XML configuration setup correctly. By using a code only solution you can avoid the whole mess with XML, web.config, or app.config changes. 

Here is a code only solution for Log4Net solution for logging to a database or file appender.

The Logging and Email Helper class to be incorporated into for example MVC project that allows for IOC containers and MOQ mocking framework… more on that on a future blog post.

The LoggingHelper.cs Class

using System;

namespace ManagerTools.Utils.Logging
{
    public class LoggingHelper
    {
        private readonly ILogging _Logging;
        private readonly ISendEmail _SendEmail;
        private readonly string _ApplicationDisplayName;

        public LoggingHelper(ILogging logging, ISendEmail sendEmail, string applicationDisplayName)
        {
            _Logging = logging;
            _SendEmail = sendEmail;
            _ApplicationDisplayName = applicationDisplayName;
        }

        public void EmailApplicationException(Exception exception)
        {
            string applicationHeaderText = string.Format("{0}: Error", _ApplicationDisplayName);
            const string USE_DEFAULT_FROM_EMAIL = "";
            string body = exception.ToString();
            _SendEmail.SendMail(USE_DEFAULT_FROM_EMAIL, applicationHeaderText, body);
        }

        public void EmailApplicationSendTo(string toEmail, string fromEmail, string fromEmailDisplay, string subject, string body )
        {
            _SendEmail.SendMail(toEmail, fromEmail, fromEmailDisplay, subject, body);
        }

        public void LogApplicationException(Exception exception)
        {
            string applicationHeaderText = string.Format("{0}: Error", _ApplicationDisplayName);
            _Logging.LogException(applicationHeaderText, exception);
        }

        public void LogApplicationWarning(string message)
        {
            _Logging.LogWarning(message);
        }

        public void LogApplicationInfo(string message)
        {
            _Logging.LogInfo(message);
        }

        public void LogApplicationProgress(string message)
        {
            _Logging.LogProgress(message);
        }

        public void LogApplicationDebug(string message)
        {
            _Logging.LogDegug(message);
        }

    }
}

The ILogging.cs Interface:

using System;

namespace ManagerTools.Utils.Logging
{
    public interface ILogging
    {
        void LogException(string message);
        void LogException(string message, Exception exception);
        void LogProgress(string message);
        void LogInfo(string message);
        void LogDegug(string message);
        void LogWarning(string message);
    }
}

The Logging.cs Class

using System;
using System.Data;
using System.IO;
using log4net;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;

namespace ManagerTools.Utils.Logging
{
    public class Logging : ILogging
    {
        private readonly ILog _Logger;

        public Logging(ILog iLog, string loggingFolderPath)
        {
            InitializeHierarchyLogManager();
            var fileAppender = GetFileAppender(loggingFolderPath);
            log4net.Config.BasicConfigurator.Configure(fileAppender);
            _Logger = iLog;
        }

        public Logging(ILog iLog)
        {
            InitializeHierarchyLogManager();
            AdoNetAppender adoNetAppender = GetAdoNetAppender();
            log4net.Config.BasicConfigurator.Configure(adoNetAppender);
            _Logger = iLog;
        }

        private void InitializeHierarchyLogManager()
        {
            var hierarchy = (Hierarchy)LogManager.GetRepository();
            hierarchy.Root.RemoveAllAppenders();
        }

        private AdoNetAppender GetAdoNetAppender()
        {
            var adoNetAppender = new AdoNetAppender
                {
                    ConnectionString = "<Enter Your Connection String Here or pass it in as a constructor argument>",
                    ConnectionType = "System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
                    CommandText = "INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)",
                    
                };

            AdoNetAppenderParameter logDateParameter = new AdoNetAppenderParameter();
            logDateParameter.DbType = DbType.DateTime;
            logDateParameter.ParameterName = "@log_date";
            logDateParameter.Layout = new RawTimeStampLayout();
            adoNetAppender.AddParameter(logDateParameter);

            AdoNetAppenderParameter threadParameter = new AdoNetAppenderParameter();
            threadParameter.DbType = DbType.String;
            threadParameter.Size = 255;
            threadParameter.ParameterName = "@thread";
            threadParameter.Layout = new Layout2RawLayoutAdapter(GetConversionPatternLayout("thread"));
            adoNetAppender.AddParameter(threadParameter);

            AdoNetAppenderParameter logLevelParameter = new AdoNetAppenderParameter();
            logLevelParameter.DbType = DbType.String;
            logLevelParameter.Size = 50;
            logLevelParameter.ParameterName = "@log_level";
            logLevelParameter.Layout = new Layout2RawLayoutAdapter(GetConversionPatternLayout("level"));
            adoNetAppender.AddParameter(logLevelParameter);

            AdoNetAppenderParameter loggerParameter = new AdoNetAppenderParameter();
            loggerParameter.DbType = DbType.String;
            loggerParameter.Size = 255;
            loggerParameter.ParameterName = "@logger";
            loggerParameter.Layout = new Layout2RawLayoutAdapter(GetConversionPatternLayout("logger"));
            adoNetAppender.AddParameter(loggerParameter);

            AdoNetAppenderParameter messageParameter = new AdoNetAppenderParameter();
            messageParameter.DbType = DbType.String;
            messageParameter.Size = 4000;
            messageParameter.ParameterName = "@message";
            messageParameter.Layout = new Layout2RawLayoutAdapter(GetConversionPatternLayout("message"));
            adoNetAppender.AddParameter(messageParameter);

            AdoNetAppenderParameter exceptionParameter = new AdoNetAppenderParameter();
            exceptionParameter.DbType = DbType.String;
            exceptionParameter.Size = 2000;
            exceptionParameter.ParameterName = "@exception";
            exceptionParameter.Layout = new Layout2RawLayoutAdapter(GetConversionPatternLayout("exception"));
            adoNetAppender.AddParameter(exceptionParameter);

            adoNetAppender.ActivateOptions();
            return adoNetAppender;
        }

        private FileAppender GetFileAppender(string loggingFolderPath)
        {
            var fileAppender = new FileAppender
            {
                AppendToFile = true,
                LockingModel = new FileAppender.MinimalLock(),
                File = Path.Combine(loggingFolderPath, "ApplicationLog.txt"),
                Layout = GetPatternLayout()
            };
            fileAppender.ActivateOptions();
            return fileAppender;
        }

        private PatternLayout GetPatternLayout()
        {
            var patterLayout = new PatternLayout
            {
                ConversionPattern = "%d [%2%t] %-5p [%-10c]   %m%n%n"
            };
            patterLayout.ActivateOptions();
            return patterLayout;
        }

        private PatternLayout GetConversionPatternLayout(string pattern)
        {
            var patternLayout = new PatternLayout
            {
                ConversionPattern =  string.Format("%{0}", pattern),
            };
            patternLayout.ActivateOptions();
            return patternLayout;
        }

        public void LogException(string message)
        {
            _Logger.Error(message);
        }

        public void LogException(string message, Exception exception)
        {
            _Logger.Error(message, exception);
        }

        public void LogInfo(string message)
        {
            _Logger.Info(message);
        }

        public void LogProgress(string message)
        {
            _Logger.Info(message);
        }

        public void LogDegug(string message)
        {
            _Logger.Debug(message);
        }

        public void LogWarning(string message)
        {
            _Logger.Warn(message);
        }

    }
}

Tags: