【发布时间】:2011-08-08 06:49:23
【问题描述】:
我的应用程序是 Windows Forms .NET 4 C# TCP/IP 服务器。它每天大约会崩溃一次,并显示一条通用的 Windows Server 崩溃消息(按关闭以关闭此应用程序)。我插入了以下代码以捕获可能导致此问题的任何异常,并将一个简单的 null 对象插入到定期调用以生成测试异常的例程中。
两件事:
- 发生测试异常时,在调试器中命中日志代码,创建并写入文件,一切正常。
- 如果没有调试器,我会收到“继续或退出”.NET 堆栈跟踪消息,无论我选择哪个,都不会创建或写入文件。
.NET 消息对我来说毫无用处。我需要崩溃的日志文件堆栈跟踪。有谁知道我该怎么做?谢谢。
static class Program
{
[STAThread]
static void Main(string[] rgszArgs)
{
//My exception handler
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CatchUnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain(rgszArgs));
}
static void CatchUnhandledException
(object sender, UnhandledExceptionEventArgs e)
{
StreamWriter sw;
DateTime dtLogFileCreated = DateTime.Now;
Exception ex;
try
{
sw = new StreamWriter("crash-" + dtLogFileCreated.Day + dtLogFileCreated.Month
+ dtLogFileCreated.Year + "-" + dtLogFileCreated.Second
+ dtLogFileCreated.Minute + dtLogFileCreated.Hour + ".txt");
ex = (Exception)e.ExceptionObject;
sw.WriteLine("### Server Crash ###");
sw.WriteLine(ex.Message + ex.StackTrace);
sw.Close();
}
finally
{
Application.Exit();
}
}
}
【问题讨论】:
-
只是挑剔,但我会将您的 streamwriter.close() 调用放入 finally 或在 using 块中使用 SW。
标签: c# .net logging exception-handling