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

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

    I know this is an old question but I think this can be useful for someone else.

    We came across a similar situation where it was required that the application shouldn't leave an empty log file if no errors occurred.

    We solved it by creating the following custom LockingModel class:

    public class MinimalLockDeleteEmpty : FileAppender.MinimalLock
    {
        public override void ReleaseLock()
        {
            base.ReleaseLock();
    
            var logFile = new FileInfo(CurrentAppender.File);
            if (logFile.Exists && logFile.Length <= 0)
            {
                logFile.Delete();
            }
        }
    }
    

    It is derived from the FileAppender.MinimalLock class that will release the lock on the log file after writing each log message.

    We added extra functionality that will delete the log file if it is still empty after the lock is released. It prevents the application from leaving empty error log files if the applications runs and exits without any errors.

    Pros

    • It will still create an empty log file during the configuration phase of Log4Net, ensuring that logging is working before the rest of the app starts. However, the log file is deleted immediately.
    • It doesn't require you to turn off logging in your config file by setting threshold value to "OFF" and than, later on, turn on logging programmatically before writing your first log event.

    Cons

    • This is most likely a slow method of managing your log files because the ReleaseLock method, and the check on the file length, will be called after every log event that is written to the log file. Only use it when you expect to have very few errors and it is a business requirement that the log file shouldn't exist when there are no errors.
    • The log files are created and deleted when empty. This might be a problem if you have other tools monitoring the log directory for file system changes. However, this was not a problem in our situation.

提交回复
热议问题