2

I want to log error in a web application designed in asp.net webforms.

Currently i use following code to log error when ever exception is raised

void Application_Error(object sender, EventArgs e) 
    { 

        // Code that runs when an unhandled error occurs


            Exception exc = Server.GetLastError();

            // Include enterprise logic for logging exceptions 
            // Get the absolute path to the log file 
            string logFile = "~/App_Data/ErrorLog.txt";
            logFile = HttpContext.Current.Server.MapPath(logFile);

            // Open the log file for append and write the log
            using (StreamWriter sw = new StreamWriter(logFile, true))
            {
                sw.WriteLine("********** {0} **********", DateTime.Now);
                if (exc.InnerException != null)
                {
                    sw.Write("Inner Exception Type: ");
                    sw.WriteLine(exc.InnerException.GetType().ToString());
                    sw.Write("Inner Exception: ");
                    sw.WriteLine(exc.InnerException.Message);
                    //sw.Write("Inner Source: ");
                    sw.WriteLine(exc.InnerException.Source);
                    if (exc.InnerException.StackTrace != null)
                    {
                      //  sw.WriteLine("Inner Stack Trace: ");
                      //  sw.WriteLine(exc.InnerException.StackTrace);
                    }
                }

                sw.Write("Exception Type: ");
                sw.WriteLine(exc.GetType().ToString());
                sw.WriteLine("Exception: " + exc.Message);
                // sw.WriteLine("Source: " + source);
                //sw.WriteLine("Stack Trace: ");
                if (exc.StackTrace != null)
                {
                 //   sw.WriteLine(exc.StackTrace);
                  //  sw.WriteLine();
                }
                // sw.Close();
            }

    }

How can i modify this code so that i can check the file size first to see if it has reached 1MB size. If logfile has reached the 1MB size then i will create another file with date label etc.

Student
  • 155
  • 5
  • 15

2 Answers2

2

You can use FileInfo in this way:

FileInfo fi = new FileInfo(logFile);
if(fi.length > 1024) {
    // create new file
}
erikscandola
  • 2,854
  • 2
  • 17
  • 24
1

Another option is to use a powerful logging library such as NLog. It allows you to specify maximum file size for a log file and also to automatically delete old files.

As you can see, these options and many other are automatically handled based on a xml configuration.

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164