getsentry / raven-csharp

Superseded by: https://github.com/getsentry/sentry-dotnet
BSD 3-Clause "New" or "Revised" License
231 stars 121 forks source link

SentryUserFactory.OnCreate never called? #249

Closed winzig closed 6 years ago

winzig commented 6 years ago

I've tried to piece together how to do custom SentryUser configuration from other issues I found reported here, but am having difficulty getting it to do anything.

In Startup.cs's ConfigureServices method, I have:

services.AddSingleton<IRavenClient, RavenClient>(
    s => new RavenClient(
        Constants.ApiUrlSentryDNWeb, 
        sentryUserFactory: new Factories.CustomUserFactory(s.GetService<IHttpContextAccessor>())
    )
);

My CustomUserFactory class looks like this:

public class CustomUserFactory : SentryUserFactory
{
    private readonly IHttpContextAccessor context;

    public CustomUserFactory(IHttpContextAccessor context)
    {
        this.context = context;
    }

    protected override SentryUser OnCreate(SentryUser user)
    {
        if (context.HttpContext.User.Identity.IsAuthenticated)
        {
            user.Username = "Custom Username";
            user.Email = "user@email.address";
        }

        return base.OnCreate(user);
    }
}

I can confirm that the constructor is called, because my breakpoint on this.context = context; gets hit, but my code never seems to execute the OnCreate method. Did I miss a configuration step somewhere?

bruno-garcia commented 6 years ago

Hi @winzig, Sending an event will eventually call the factory (and your overriden OnCreate): https://github.com/getsentry/raven-csharp/blob/d8e6938548d0d0fbd6a3b5541f6caddaee04be5b/src/app/SharpRaven/RavenClient.cs#L333

but only if the Packet had not yet defined a user. By any chance, do you have also a custom JsonPacketFactory?

here: https://github.com/getsentry/raven-csharp/blob/d8e6938548d0d0fbd6a3b5541f6caddaee04be5b/src/app/SharpRaven/RavenClient.cs#L224

winzig commented 6 years ago

@bruno-garcia Thanks for your help! Looking into your questions led me to discover the issue... we were defining two instances of RavenClient. One in Startup.cs with the user factory setup correctly. A second one that was more of a static RavenClient with no factory defined. This was the one being called, instead of pulling in our primary one via:

var ravenClient = context.RequestServices.GetService<IRavenClient>()

Now that we're doing that, all is well.

bruno-garcia commented 6 years ago

Glad it worked out!