Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging username with Elmah for WCF Webservices

We are using the approach described here to log our webservice errors with Elmah. And this actually works, but sadly the username beeing logged is empty.

We did some debugging and found, that when logging the error in the ErrorHandler the HttpContext.Current.User has the correct User set.

We also tried:

HttpContext context = HttpContext.Current;
ErrorLog.GetDefault(context).Log(new Error(pError, context));

and

ErrorLog.GetDefault(null).Log(new Error(pError));

Without success.

Any ideas on how we can make Elmah log the username?

On a sidenote, when logging the error directly within the Webservice, the username is logged as expected. But taking this approach is not very DRY.

like image 899
Thomas Avatar asked Oct 12 '10 07:10

Thomas


2 Answers

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.

like image 118
Shay Erlichmen Avatar answered Nov 18 '22 06:11

Shay Erlichmen


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();
    }
}
like image 25
ThomasArdal Avatar answered Nov 18 '22 06:11

ThomasArdal