2009-10-02

Programmatically configure Log4net with two rolling file appenders

public static class LogBootstrapper
{
    public static void Bootstrap()
    {
        RootLogger.AddAppender(CreateRollingFileAppender(Level.All));
        RootLogger.AddAppender(CreateRollingFileAppender(Level.Info));
        RootLogger.Repository.Configured = true;
    }

    private static Logger RootLogger
    {
        get { return ((Hierarchy)LogManager.GetRepository()).Root; }
    }

    private static RollingFileAppender CreateRollingFileAppender(Level level)
    {
        var usingFileName = string.Format("logs\\MyProject_{0}-{1}-{2}_{3}.log",
        DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, level.Name);
        var layout = new PatternLayout("[%level] %message%newline");
        var rollingFileAppender = new RollingFileAppender
        {
            Layout = layout,
            AppendToFile = true,
            RollingStyle = RollingFileAppender.RollingMode.Date,
            File = usingFileName,
            ImmediateFlush = true,
            Threshold = level
        };
        rollingFileAppender.ActivateOptions();

        return rollingFileAppender;
    }
}

Beats XML config IMHO.

No comments:

Post a Comment

Post a Comment