November 11, 2008

Configuring Log4Net Programmatically

Configuring Log4Net Programmatically Set the logging level of the logger
public string LoggingLevel
{
 get
 {
  log4net.Repository.Hierarchy.Logger logger = (log4net.Repository.Hierarchy.Logger)m_log.Logger;
  return logger.Level.Name;
 }
 set
 {
  if (!string.IsNullOrEmpty(value))
  {
   log4net.Repository.Hierarchy.Logger logger = (log4net.Repository.Hierarchy.Logger)m_log.Logger;
   logger.Level = logger.Hierarchy.LevelMap[value];
  }
 }
}
Example configuring Appenders for a log
#region log4net

internal class LoggingConfigurer
{
    public static readonly string DefaultLayoutPattern = "%d [%t]%-5p %c [%x] - %m%n ";
    public static readonly string DefaultFileName = "XXXLog.txt";
    public static readonly string FileAppendarName = "XXXRFA";

    // Configure the logger programmatically. 
    public static void ConfigureLogging(ILog log)
    {
        bool isConfigured = log.Logger.Repository.Configured;
        if (!isConfigured)
        {
            // Setup RollingFileAppender
            RollingFileAppender rollingFileAppender = new RollingFileAppender();
            rollingFileAppender.Layout = new PatternLayout(DefaultLayoutPattern);
            rollingFileAppender.MaximumFileSize = "100KB";
            rollingFileAppender.MaxSizeRollBackups = 5;
            rollingFileAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
            rollingFileAppender.AppendToFile = true;
            rollingFileAppender.File = DefaultFileName;
            rollingFileAppender.Name = FileAppendarName;
            rollingFileAppender.ActivateOptions(); // IMPORTANT, creates the file
            BasicConfigurator.Configure(rollingFileAppender);
#if DEBUG
            // Setup TraceAppender
            TraceAppender ta = new TraceAppender();
            ta.Layout = new PatternLayout(DefaultLayoutPattern);
            BasicConfigurator.Configure(ta);
#endif
        }
    }
}

#endregion log4net  
usage, when initialising your logger:
log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
LoggingConfigurer.ConfigureLogging(log);
Here is an example where the log file name is changed:
private static void RenameLogFile(string newLogFileName)
{
    var rfa = LogManager.GetRepository().GetAppenders().
         OfType<RollingFileAppender>().
         FirstOrDefault(appender => 
            appender.Name == LoggingConfigurer.FileAppendarName);
    if (rfa != null)
    {
        rfa.File = newLogFileName + ".txt";
        rfa.ActivateOptions();
    }
}

No comments: