gpt4 book ai didi

c# - 使用asp.net检查日志文件大小和日志写入

转载 作者:行者123 更新时间:2023-11-30 21:52:42 25 4
gpt4 key购买 nike

我想在用 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 大小,那么我将创建另一个带有日期标签等的文件。

最佳答案

您可以这样使用 FileInfo:

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

关于c# - 使用asp.net检查日志文件大小和日志写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34587440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com