我想在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大小。如果logfile已达到1MB大小,那么我将创建另一个带有日期标签等的文件。
答案 0 :(得分:2)
您可以这样使用FileInfo:
FileInfo fi = new FileInfo(logFile);
if(fi.length > 1024) {
// create new file
}
答案 1 :(得分:1)
另一个选择是使用强大的日志库,例如np.random.permutation
。它允许您为日志文件指定NLog,并自动maximum file size。
如您所见,这些选项和许多其他选项都是基于xml配置自动处理的。