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

前端 未结 7 804
生来不讨喜
生来不讨喜 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:23

    The following worked for me.The first call to OpenFile() occurs when the logger is configured. Subsequent calls are when actual log message is generated.

    class CustomFileAppender : RollingFileAppender
    {
        private bool isFirstTime = true;
        protected override void OpenFile(string fileName, bool append)
        {
            if (isFirstTime)
            {
                isFirstTime = false;
                return;
            }
    
            base.OpenFile(fileName, append);
        }
    }
    

    And in the config file, change the appender

    
    
    ...
    
    

    The sequence from log4Net source is as below:


    • The first call to OpenFile() is because of ActivateOptions() called from FileAppender's constructor.
    • When log message is generated, AppenderSkeleton's DoAppend() calls PreAppendCheck()
    • PreAppendCheck() is overridden in TextWriterAppender, the base of FileAppender.
    • The overridden PreAppendCheck() calls virtual PrepareWriter if the file is not yet open.
    • PrepareWriter() of FileAppender calls SafeOpenFile() which inturn calls OpenFile()

提交回复
热议问题