log4net正在捕获除堆栈跟踪之外的所有内容

时间:2016-05-17 13:55:50

标签: c# asp.net log4net

我对Log4Net完全不熟悉。我已经能够实现我在​​网上找到的以下代码。它在捕获和保存数据方面工作正常,即日期,记录的用户,IP地址......

唯一的问题是“例外”字段为空白。我想捕获堆栈跟踪

public void Application_Error(object sender, EventArgs e)
    {
        //Fires when an error occurs
        var redirectUrl = "~/Error/GenericError.aspx";
        var httpException = (HttpException)Server.GetLastError();
        int httpCode = httpException.GetHttpCode();

        log4net.GlobalContext.Properties("ipaddress") 
                                    = Request.ServerVariables("remote_addr");
        log4net.GlobalContext.Properties("thread") = Request.Url.AbsoluteUri;
        log4net.GlobalContext.Properties("userid") = User.Identity.Name;

        var ctx = HttpContext.Current;
        var _url = ctx.Request.Url.ToString();
        log4net.GlobalContext.Properties("url") = _url;
        log4net.GlobalContext.Properties("browser") = ctx.Request.Browser.Browser;

        log4net.ILog log = log4net.LogManager.GetLogger(this.GetType());
        log.Error(httpException.Message);


        if ((httpCode == 404))
        {
            redirectUrl = "~/Error/FileNotFound.aspx";
        }
        else if ((httpCode == 403))
        {
            redirectUrl = "~/Error/UnauthorizedAccess.aspx";
        }
        else
        {
            var message = string.Empty;
            if (httpException is HttpRequestValidationException)
            {
                message = "A potentially dangerous Request.Form value"
                                    + " was detected from the client.";
            }
            else
            {
                message = httpException.Message;
            }
            redirectUrl = "~/Error/GenericError.aspx?msg=" + message;
        }

        Server.ClearError();
        Server.Transfer(redirectUrl);
    }

这是webconfig的log4net部分

 <parameter>
    <parameterName value="@exception" />
    <dbType value="String" />
    <size value="2000" />
    <layout type="log4net.Layout.ExceptionLayout" />
  </parameter>

感谢您的帮助

1 个答案:

答案 0 :(得分:4)

您需要使用overload of Error that lets you pass the exception along with the message:

  

使用错误级别记录消息对象,包括作为参数传递的异常的堆栈跟踪。

所以你的代码是:

log.Error("Error in global handler", httpException); // or other message