log4net: How to set logger file name dynamically?

前端 未结 2 682
隐瞒了意图╮
隐瞒了意图╮ 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:

    
        
        
        
        
        
        
        
            
        
    
    

    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

提交回复
热议问题