如何记录堆栈跟踪?

时间:2015-02-02 16:47:33

标签: asp.net iis

如果发生500错误,我怎样才能增加日志级别以记录堆栈跟踪?

在我的代码或IIS的网站配置中可以做些什么吗?

3 个答案:

答案 0 :(得分:0)

您可以通过捕获Exception并访问StackTrace属性在后面的代码中执行此操作。它看起来像这样:

     try
        {
           //your code 
        }
     catch( Exception ex )
        {

            Console.WriteLine( 
                "\nStackTrace ---\n{0}", ex.StackTrace );
        }

这将堆栈跟踪写入控制台窗口。

为了将消息写入日志文本文件,您可以执行类似这样的操作

public static void LogException(Exception exc, string source)
{

    // 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
    StreamWriter sw = new StreamWriter(logFile, true);
    sw.WriteLine("********** {0} **********", DateTime.Now);
    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();
}

Resource

所以把两者放在一起将会做你想做的事情:

     try
        {
           //your code 
        }
     catch( Exception ex )
        {

            string logFile = "App_Data/ErrorLog.txt";
    logFile = HttpContext.Current.Server.MapPath(logFile);

    // Open the log file for append and write the log
    StreamWriter sw = new StreamWriter(logFile, true);
    sw.WriteLine("********** {0} **********", DateTime.Now);
    sw.Write("Exception Type: ");
    sw.WriteLine(exc.GetType().ToString());
    sw.WriteLine("Exception: " + ex.Message);
    sw.WriteLine("Source: " + source);
    sw.WriteLine("Stack Trace: ");
    if (exc.StackTrace != null)
    {
        sw.WriteLine(ex.StackTrace);
        sw.WriteLine();
    }
    sw.Close();
        }

答案 1 :(得分:0)

IIS默认情况下已经记录了这一点 - 查看IIS服务器上的事件日志。

您可以捕获此内容并将其发送到您希望使用ASP.NET Health Monitoring的任何位置,但您可能还希望在ELMAH处理时使用更好的异常处理程序。

答案 2 :(得分:0)

使用

可以很好地支持记录错误

Microsoft.Practices.EnterpriseLibrary.Logging