Raw*_*Bag 3 .net c# logging exception-handling
我的应用程序是Windows Forms .NET 4 C#TCP/IP服务器.它每天都会崩溃一次,发生一般的Windows Server崩溃消息(按关闭以关闭此应用程序).我插入以下代码来捕获可能导致此问题的任何异常,并且我将一个简单的null Object插入到一个定期调用以生成测试异常的例程中.
两件事情:
.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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您需要Application.ThreadException事件.
AppDomain未发送的异常事件捕获抛出的未处理异常 - 例如,Main
方法抛出的任何异常,但是在Application.Run
内部处理异常 - 这意味着Application.Run
不会因事件处理程序中的异常而抛出异常,因此CatchUnhandledException
永远不会运行.
这意味着如果ThreadException
处理程序能够从异常中恢复,那么应用程序将继续正常运行(如果抛出异常Application.Run
将无法恢复).由于我不明白的原因,这种行为在调试时是不同的..调试时,此行为已更改,以便抛出异常,允许您在Visual Studio中立即调试异常 - 这就是您的未处理异常处理程序在调试时正在运行的原因.
请注意,上述CatchUnhandledException
处理程序将捕获应用程序域中后台线程抛出的异常.
另请参见Application.SetUnhandledExceptionMode.
归档时间: |
|
查看次数: |
4825 次 |
最近记录: |