0
votes

For this app (CMS) Log4net is configured in Config/log4net.config.

I need to set the path for where the log file should be placed dynamically at runtime.

I have tried adding the following code to global.asax (and OnApplicationStarting)

log4net.GlobalContext.Properties["path"] = "testlog";
log4net.Config.XmlConfigurator.Configure();

plus changed the configuration to

<file type="log4net.Util.PatternString"  value="c:\Logs\%property{path}\AppLog.log" />

in log4net.config

It starts with creating a directory c:\Logs\(null)\AppLog.log - and begins logging - and after a short while it creates the wanted directory - c:\Logs\testlog\AppLog.log - and continues the logging in this directory.

I seem not to be able to hook in before the logging starts. Anybody having a solution or idea about how I should do it - so I do not get the (null) directory first?

Can i somehow access a value set in web.config and use this as the dynamic part in the folder name?

1
Any progress with that? - Offir

1 Answers

1
votes

You need to put this:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

in AssemblyInfo.cs

and add the property before getting the logger. Here is a working example:

My config:

<appender name="RollingFileAppender" type="log4net.appender.RollingFileAppender">
            <file type="log4net.Util.PatternString" value="C:\MyLogs\%property{LogFileName}.txt"/>
            <appendToFile value="true"/>
            <rollingStyle value="Size"/>
            <maximumFileSize value="10MB"/>
            <maxSizeRollBackups value="5"/>
            <staticLogFileName value="true"/>
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date{ABSOLUTE} [%logger] %level - %message%newline%exception"/>
            </layout>
        </appender>

And c# code:

using System;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace Log4NetConsoleApplication
{
    class Program
    {

        static void Main(string[] args)
        {
            log4net.GlobalContext.Properties["LogFileName"] = "log";    

            log4net.ILog log = LogHelper.GetLogger();

            Console.WriteLine("hello world");

            log.Error("This is my error message");

            Console.ReadLine();
        }
    }
}