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;
      return true;  // Appender found and name changed to NewFilename
  return false; // appender not found
ChangeLogFileName("RollingFileAppender", "MyLogName.log");

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

//App.config configuration
<?xml version="1.0"?>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,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"/>
    <logger name="MyCompany">
      <appender-ref ref="RollingFileAppender"/>


Post a Comment

Popular posts from this blog

Parse XML to dynamic object in C#

Parse XML to object model in C# using XSD utility