小编Raw*_*Bag的帖子

C#未处理的异常处理程序,尝试写入日志文件

我的应用程序是Windows Forms .NET 4 C#TCP/IP服务器.它每天都会崩溃一次,发生一般的Windows Server崩溃消息(按关闭以关闭此应用程序).我插入以下代码来捕获可能导致此问题的任何异常,并且我将一个简单的null Object插入到一个定期调用以生成测试异常的例程中.

两件事情:

  1. 当发生测试异常时,在调试器中命中日志代码,创建并写入文件,一切都很好.
  2. 没有调试器,我得到一个"继续或退出"的.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 + …
Run Code Online (Sandbox Code Playgroud)

.net c# logging exception-handling

3
推荐指数
1
解决办法
4825
查看次数

标签 统计

.net ×1

c# ×1

exception-handling ×1

logging ×1