log4net: How to set logger file name dynamically?

前端 未结 2 683
隐瞒了意图╮
隐瞒了意图╮ 2021-02-18 23:11

This is a really common question, but I have not been able to get an answer to work. Here is my configuration file:

<         


        
相关标签:
2条回答
  • 2021-02-18 23:57

    you can use this function : in this function first get file location that you set in webconfig and after that you can add any path that you want ! like Date ! our Customer ! or .....

    WebConfig:

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="C:\\t4\\"/>
        <appendToFile value="true"/>
        <rollingStyle value="Composite"/>
        <datePattern value="_yyyy-MM-dd.lo'g'"/>
        <maxSizeRollBackups value="10"/>
        <maximumFileSize value="1MB"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date User:%identity IP:%X{addr} Browser: %X{browser} Url: %X{url} [%thread] %-5level %c:%m%n"/>
        </layout>
    </appender>
    

    Function:

    public static void ChangeFileLocation(string _CustomerName,string _Project)
    {
        XmlConfigurator.Configure();
        log4net.Repository.Hierarchy.Hierarchy h =(log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository();
    
        foreach (IAppender a in h.Root.Appenders)
        {
            if (a is FileAppender)
            {
                FileAppender fa = (FileAppender)a;
                string sNowDate=  DateTime.Now.ToLongDateString();
                // Programmatically set this to the desired location here
                string FileLocationinWebConfig = fa.File;
                string logFileLocation = FileLocationinWebConfig + _Project + "\\" + _CustomerName + "\\" + sNowDate + ".log";
    
                fa.File = logFileLocation;
                fa.ActivateOptions();
                break;
            }
        }
    }
    

    and result like this : C:\t4\TestProject\Customer1\Saturday, August 31, 2013.log

    0 讨论(0)
  • 2021-02-19 00:05

    What about to use "%property" to define a dynamic 'tag' to the file name (at runtime) ?

    <file type="log4net.Util.PatternString" value="~/App_Data/%property{LogName}" />
    

    Explained here: Best way to dynamically set an appender file path

    0 讨论(0)
提交回复
热议问题