How can I clear log4net log file?

12,230

Solution 1

It is not supported "out of the box" from log4net. However, you could using the RollingFileAppender and create a manual class/method to clean up/delete the log file.

For reference, Log4Net: set Max backup files on RollingFileAppender with rolling Date

Another approach to avoid the file being locked would be to set the minimal locking level on the log file via:

<lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> 

Solution 2

I had this issue, too.

You need this in your config:

<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />

Solution 3

If you don't want to suffer the performance implications of having a minimal lock (see answer), then you can temporarily configure the appenders to use a minimal lock, delete the files, and then bring the default behavior back.

Example when you're only using RollingFileAppenders:

// Release the lock on the log4net log files
var appenders = log4net.LogManager.GetRepository().GetAppenders();
foreach (var appender in appenders)
{
    var rollingFileAppender = appender as log4net.Appender.RollingFileAppender;
    if (rollingFileAppender != null)
    {
        rollingFileAppender.ImmediateFlush = true;
        rollingFileAppender.LockingModel = new log4net.Appender.FileAppender.MinimalLock();
        rollingFileAppender.ActivateOptions();
    }
}

The files are now free to be deleted without problems.

Solution 4

Thanks guys I succeed clear the log. In the appender block of the log configuration file I added that line:

<lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> 

The code that clear the log file is:

        RollingFileAppender fileAppender = LogManager.GetRepository()
                        .GetAppenders().FirstOrDefault(appender => appender is RollingFileAppender) as RollingFileAppender;


        if (fileAppender != null && File.Exists(((RollingFileAppender)fileAppender).File))
        {
            string path = ((RollingFileAppender)fileAppender).File;
            log4net.Appender.FileAppender curAppender = fileAppender as log4net.Appender.FileAppender;
            curAppender.File = path;

            FileStream fs = null;
            try
            {
                fs = new FileStream(path, FileMode.Create);
            }
            catch(Exception ex)
            {
                (log4net.LogManager.GetLogger(this.GetType())).Error("Could not clear the file log", ex);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }

            }
        }

Thank you all

Share:
12,230
Amir Brand
Author by

Amir Brand

Updated on July 28, 2022

Comments

  • Amir Brand
    Amir Brand almost 2 years

    I am working with log4net. I wants to add a button in my GUI that when the user click on that button, the log file will cleared. How can I do that?

    Thanks alot