Logging User information in Nancy
jculverwell
Posted on
Nov 03 2015
Hi All,
Was wondering if anyone could point my in the right direction with regards to attaching user information to exceptions logged via nancyfx.
Thanks
Jim
Phillip Haydon
Posted on
Nov 04 2015
Hey Jim,
Are you using Forms auth with Nancy?
jculverwell
Posted on
Nov 05 2015
Hi Phillip,
Thank you for reaching out. I'm using StatelessAuth with JWTs
//From my startup class app.RequiresStatelessAuth( new JWTTokenValidator(), new StatelessAuthOptions()
//From Request StartUp
var owinEnvironment = context.GetOwinEnvironment(); var user = owinEnvironment["server.User"] as ClaimsPrincipal; if (user != null) {
context.CurrentUser = new User()
{
UserName = user.Identity.Name,
Claims = user.Claims.Where(x => x.Type == ClaimTypes.Role).Select(x => x.Value),
UserID = Convert.ToInt32(user.Claims.Where(x => x.Type == ClaimTypes.NameIdentifier).Select(x => x.Value).FirstOrDefault()),
EmailAddress = user.Claims.Where(x => x.Type == ClaimTypes.Email).Select(x => x.Value).FirstOrDefault(),
};
Cheers
Jim
Phillip Haydon
Posted on
Nov 05 2015
Ahh ok cool.
This is pretty rough and untested, but should lead you on the right path.
public class RaygunLoggingRegistration : IApplicationStartup
{
private static readonly RaygunClient Client;
static RaygunLoggingRegistration()
{
Client = new RaygunClient("your api key...");
}
public void Initialize(IPipelines pipelines)
{
if (Client == null)
{
return;
}
var raygunItem = new PipelineItem<Func<NancyContext, Exception, dynamic>>("Raygun", (context, exception) =>
{
var user = context.CurrentUser as User;
if (user != null)
{
... build the user ...
}
Client.SendInBackground(context, exception, raygunUser);
return null;
});
pipelines.OnError.AddItemToStartOfPipeline(raygunItem);
}
}
.
So Nancy will automatically find and register the IApplicationStartup file.
Create a static instance of the Raygun Client ( I forget what all the object naming is, I just wrote this off top of my head )
Create a Pipeline item, which gives you access to the current user, if there's a logged in user, build the required raygun user object, and pass that in when sending the request.
Hope that helps.
jculverwell
Posted on
Nov 05 2015
Hi Phillip,
Really appreciate your help. Loving Nancy and Raygun. Let me know if there is anywhere I can leave a beer donation.
Cheers
Jim