0

I have a C# application which uses log4net to write some log outputs in a file names "logfile.txt" residing in the application directory. I want to empty the contents of the file as soon as it reaches a size of 10GB.

For that I'm using a timer which keeps checking whether the size of the file crosses 10GB. But I cannot perform any operation on "logfile.txt" since it is being used by other threads to write log outputs and it's throwing me,

System.IO.IOException "The process cannot access the file 'C:\Program Files\MyApps\TestApp1\logfile.txt' because it is being used by another process."

Here is the code of the timer which checks the size of the file "logfile.txt"

private void timer_file_size_check_Tick(object sender, EventArgs e)
{
    try
    {
        string log_file_path = "C:\\Program Files\\MyApps\\TestApp1\\logfile.txt";
        FileInfo f = new FileInfo(log_file_path);
        bool ex;
        long s1;
        if (ex = f.Exists)
        {
            s1 = f.Length;
            if (s1 > 10737418240)
            {
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();

                File.Delete(log_file_path);
                //File.Create(log_file_path).Close();
                //File.Delete(log_file_path);
                //var fs = new FileStream(log_file_path, FileMode.Truncate);
            }
        }
        else
        {
            MDIParent.log.Error("Log file doesn't exists..");
        }
    }
   catch (Exception er)
    {
        MDIParent.log.Error("Exceptipon :: " + er.ToString());
    } 
}
Nordehinu
  • 338
  • 1
  • 3
  • 11
Biswarup Dass
  • 193
  • 1
  • 5
  • 19
  • you mixed up try/catch. Do the catching under the try statement – joppiesaus Nov 15 '14 at 09:30
  • 1
    Why don't you reconfigure the application to maintain a logfile size of no more than 10 GB? You can do this with a `RollingFileAppender` and the `maximumFileSize` option. The whole point of log4net is that it gives you the flexibility to configure logging independently from application logic. – Jeroen Mostert Nov 15 '14 at 09:31
  • MDIParent.log is a ILog type member that writes the respective logs to the file "logfile.txt". What i want to do is empty the contents of this file when the size reaches 10GB. – Biswarup Dass Nov 15 '14 at 09:33
  • @ Jeroen Mostert can you guide me through the solution u gave? – Biswarup Dass Nov 15 '14 at 09:34
  • Do i need to change the log config from app.config where i have made other log configurations? – Biswarup Dass Nov 15 '14 at 09:35

1 Answers1

1

You shouldn't delete a log file on your own because log4net can do it for you. If you use RollingFileAppender you can specify the maximum file size (maximumFileSize property). Additionally if you set maxSizeRollBackups property to 0, then the log file will be truncated when it reaches the limit. Please look at this question for an example.

Michał Komorowski
  • 6,198
  • 1
  • 20
  • 24