ASP.NET C#

Configuring Log4Net file appender in C#

I’ll be honest. Setting up Log4net for ASP.NET MVC apps is a pain. For better or worse, Log4net doesn’t error-out whenever things aren’t set up correctly; it fails silently (really it’s for the better, but it gets annoying!). Lately, I’ve been using this C# snippet to configure my logging. Just call the following method in your Global.asax.cs and you should be up and ready to go with Log4net!

private static void SetupLogging(bool removeAllOtherLoggers = false)
{
    var logFolder = GetSetting("LogFolder", @"c:\logs");
    var logFile = GetSetting("LogFile", @"c:\logs\MyLog.txt");
    if (!Directory.Exists(logFolder))
    {
        Directory.CreateDirectory(logFolder);
    }
    var hierarchy = (Hierarchy) LogManager.GetRepository();
    if (removeAllOtherLoggers)
    {
        hierarchy.Root.RemoveAllAppenders();
    }
    
    var fileAppender = new RollingFileAppender
    {
        AppendToFile = true,
        RollingStyle = RollingFileAppender.RollingMode.Size,
        LockingModel = new FileAppender.MinimalLock(),
        File = logFile,
        DatePattern = "yyyyMMdd",
        MaxSizeRollBackups = 10,
        MaximumFileSize = "5MB",
        Threshold = Level.Debug
    };
    var pl = new PatternLayout
    {
        ConversionPattern = "%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"
    };
    pl.ActivateOptions();
    fileAppender.Layout = pl;
    fileAppender.ActivateOptions();

    BasicConfigurator.Configure(fileAppender);
    Trace.AutoFlush = true;
}

Leave a Reply

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