Thursday, 14 June 2012

Update Log4Net file name programmatically

//update log file name
public static bool ChangeLogFileName(string appenderName, string newFilename)
{            
  var rootRepository = log4net.LogManager.GetRepository();
  foreach (var appender in rootRepository.GetAppenders())
  {
    if (appender.Name.Equals(appenderName) && appender is log4net.Appender.FileAppender)
    {
      var fileAppender = appender as log4net.Appender.FileAppender;
      fileAppender.File = newFilename;
      fileAppender.ActivateOptions();
      return true;  // Appender found and name changed to NewFilename
    }
  }
  return false; // appender not found
}
//usage
ChangeLogFileName("RollingFileAppender", "MyLogName.log");

Sample log4net configuration from App.config, for more info see this post

//App.config configuration
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  </configSections>
  
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Log\\App.log"/>
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value=".yyyyMMdd"/>
      <maxSizeRollBackups value="7"/>
      <staticLogFileName value="true"/>
      <threshold value="INFO"/>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p %c.%M():%L - %m%n"/>
      </layout>
    </appender>
    <logger name="MyCompany">
      <appender-ref ref="RollingFileAppender"/>
    </logger>
  </log4net>
  
</configuration>

3 comments:

Anonymous said...

good work

Anonymous said...

Very good work

Anonymous said...

Perfect. Saved me some time. Thanks.

Post a Comment