Logging username with Elmah for WCF Webservices

佐手、 提交于 2019-11-30 14:48:33

Elmah take the user from Thread.CurrentPrincipal.Identity.Name and not from HttpContext.Current.User.

Since there ins't a convenient way to add custom data to Elmah, I would suggest recompiling the code, and calling HttpContext.Current.User instead.

This is a question that I see over and over again. While re-compiling the code is a possibility, I would rather suggest using features built into ELMAH already, as explained in my blog post Enrich ELMAH errors using error filtering hook.

In your case, setting the User property on all errors, can be achieved by adding the ErrorLog_Filtering-method:

void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs args)
{
    var httpContext = args.Context as HttpContext;
    if (httpContext != null)
    {
        var error = new Error(args.Exception, httpContext);
        error.User = httpContext.User.Identity.Name;
        ErrorLog.GetDefault(httpContext).Log(error);
        args.Dismiss();
    }
}

As an alternative to recompile Elmah, we can use a global method, which populates Thread.CurrentPrincipal.Identity.Name before calling elmah.

public static void LogError(Exception exception, string username)
{
    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), new string[] {});
    Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!