How to set log4net LockingModel programmatically after loading with XmlConfigurator?

6.5k views Asked by At

I have this XML log4net configuration:

  <log4net>
    <appender name="myAppender" type="log4net.Appender.RollingFileAppender">
      <file value="mylog.txt" />
    </appender>
    <root>
      <level value="DEBUG" />
        <appender-ref ref="myAppender" />
    </root>
  </log4net>

I load this configuration with the C# line below, and it works well:

log4net.Config.XmlConfigurator.Configure(path);

PROBLEM: Now I want to set the lockingModel to MinimalLock. Programmatically, not in XML.
How to do it?

That would be the equivalent of adding <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> in the XML configuration.

2

There are 2 answers

2
stuartd On BEST ANSWER
// assumes there are not multiple file appenders defined
var appender = log4net.LogManager.GetRepository()
                                 .GetAppenders()
                                 .OfType<FileAppender>()
                                 .SingleOrDefault();

if (appender != null)
{
     appender.LockingModel = new FileAppender.MinimalLock();
}
1
Alexander.sako On
    <appender name="text" type="log4net.Appender.RollingFileAppender,log4net">
        <param name="File" value="c:\system-name.log"/>
        <param name="AppendToFile" value="true"/>
        <rollingStyle value="Date"/>
        <staticLogFileName value="true"/>
        <datePattern value="'.'yyyy-MM-dd"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %5p %c{1}:%L - %m%n"/>
        </layout>
enter code here
        <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    </appender>