How to disable creation of empty log file on app start?

前端 未结 7 812
生来不讨喜
生来不讨喜 2020-11-30 07:04

I have configured log4net in my app successfully but one thing is a little bit annoying for me.

The log file is created (empty) after my app start even if no error o

7条回答
  •  情歌与酒
    2020-11-30 07:34

    Another method that is quite simple is described in this message of the mailing list archive

    Basically, with log4net, the log file is created when the logger is configured. To configure it to do otherwise is a bit hacky. The solution is to defer the execution of the configuration. The message above suggests doing the following when setting up the logger:

    private static ILog _log = LogManager.GetLogger(typeof(Program));
    public static ILog Log
    {
        get
        {
            if(!log4net.LogManager.GetRepository().Configured)
                log4net.Config.XmlConfigurator.Configure(new FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile));
            return _log;
        }
    }
    

    I usually configure log4net with the assembly attribute, which configures the logger automatically (thus creating the log file), and a simple getter for the log:

    [assembly: log4net.Config.XmlConfigurator(Watch = true)]
    ...
    public static log4net.ILog Log { get { return _log; } }
    private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    

    But removing that and adding in the above getter with the additional logic instead solved the problem for me.

    Note: in general I agree that in most cases it would be best to configure the logger and create the file (and even write to it) on application startup.

提交回复
热议问题