Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4net log4net.Util.PatternString configure from code

I have a console application with log4net, and I would like to add logfile name from code. (I use threads later)

class Program
{
    static void Main(string[] args)
    {
        {
            log4net.GlobalContext.Properties["fname"] = "aaaa";
            log4net.Config.XmlConfigurator.Configure();
        }
    }
}

<appender name="default" type="log4net.Appender.RollingFileAppender">
   <file type="log4net.Util.PatternString" value="d:\\TEMP\\default_%property{fname}.log"/>
...
</appender>

And I get (null).

Thanks for your help.

like image 422
ngi Avatar asked Aug 17 '26 12:08

ngi


1 Answers

This should work

I used log4net 1.2.13.0. One thing you should consider is adding a internal debug for log4net which will tell you the actual error.

class Program
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static void Main(string[] args)
        {
            log4net.GlobalContext.Properties["fname"] = "aaaa";

            log4net.Config.XmlConfigurator.Configure();
            log.Debug("Test");
        }
    }

Config section

<configuration>      
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <log4net debug="true">
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="D:\default_%property{fname}.log"/>
      <appendToFile value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>    
    <root>
      <priority value="ALL"/>
      <appender-ref ref="RollingFileAppender"/>
    </root>    
  </log4net>
  <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add
            name="textWriterTraceListener"
            type="System.Diagnostics.TextWriterTraceListener"
            initializeData="E:\USERS\vivek.meka\Documents\Visual Studio 2015\Projects\log4net.txt" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>
like image 178
Vivekh Avatar answered Aug 19 '26 10:08

Vivekh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!