Add a Session Variable or Custom field to the Elmah Error Log table

送分小仙女□ 提交于 2019-12-10 20:50:02

问题


I want to add my own session variable to elmah error log table and display it. I already have modified the source code and added the new fields to Error.cs and other fields but I don't know but when I assign an HttpContext.Current.Session["MyVar"].tostring() value to my field in the constructor it stops logging exceptions and does not log any exception.

I just need to get the value of the session variable is there other way for this ? I read a post which he added fields for the email but it does not say where exactly should I get the session value. I also read that Session and Cookies ar e logged by default by Elmah but I dont know how to access them..Thanks to everyone for their help.


回答1:


Without seeing your source code I can only make assumptions, but I think Elmah stops logging because you get an exception. This might happen because the Session property is null. The session is only available after the PostAcquireRequestState event and therefore you cannot count on this property to be always available.

I tried this myself and wrote a method like this:

private static Dictionary<string, object> CopySession(HttpSessionState session)
{
    if (session == null || session.Count == 0)
        return null;

    Dictionary<string, object> copy = new Dictionary<string, object>(session.Count);
    foreach (var key in session.Keys)
    {
        string name = key.ToString();
        copy.Add(name, session[name]);
    }

    return copy;
}

I call this method in the constructor of the Error class like this:

// _session is a new field that I added like this:
// private Dictionary<string, object> _session;
_session = CopySession(context.Session);

(just after server variables and the other context stuff gets copied. You will probably need to change the IClonable implementation to copy the _session field, too.)

In my tests this works as expected. I only checked in the SqlErrorLog class, but this will be the same for all the other ErrorLog classes: The error object contained all my session variables and I could store them in the database in whatever way I wanted.




回答2:


I haven't used it, but this was asked before and apparently there is a patch, you might want to try that.



来源:https://stackoverflow.com/questions/2685657/add-a-session-variable-or-custom-field-to-the-elmah-error-log-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!