使用asp.net进行日志文件大小检查和日志写入

本文关键字:日志 文件大小 检查和 asp net 使用 | 更新日期: 2023-09-27 18:28:48

我想在用asp.net webforms设计的web应用程序中记录错误。

目前,我使用以下代码来记录异常时的错误

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();
            }
    }

我如何修改这个代码,以便我可以首先检查文件大小,看看它是否已经达到1MB大小。如果日志文件已达到1MB大小,那么我将创建另一个带有日期标签等的文件。

使用asp.net进行日志文件大小检查和日志写入

您可以通过以下方式使用FileInfo:

FileInfo fi = new FileInfo(logFile);
if(fi.length > 1024) {
    // create new file
}

另一个选项是使用强大的日志库,如NLog。它允许您指定日志文件的最大文件大小,还可以自动删除旧文件。

正如您所看到的,这些选项和许多其他选项都是基于xml配置自动处理的。