【问题标题】:log4net is capturing everything except the stack trace [duplicate]log4net 正在捕获除堆栈跟踪之外的所有内容[重复]
【发布时间】:2016-05-17 22:01:45
【问题描述】:

我对 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>

感谢您的帮助

【问题讨论】:

  • 你说的是哪个空白异常字段?
  • 表中有一个字段叫Exception。将行更改为@stuartd 提供的答案,message 和 exception 字段现在正在填充。

标签: c# asp.net log4net


【解决方案1】:

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

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

所以你的代码是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    相关资源
    最近更新 更多