How do I configure sentry for a new project?

  • Page Owner: Not Set
  • Last Reviewed: 2019-11-25

How should I set up global error logging for my project? How do I set up Sentry? How do I configure Sentry to filter out annoyance exceptions?


Answer

We no longer have a CMS-specific implementation. We just use the Sentry.AspNet package directly.

If Blend.Sentry or any other Blend created Sentry package is installed, remove it first along with the Raven client

For CMS 12 / .NET 5 and above:

  1. Install Sentry.AspNetCore package.
  2. Add a Sentry section to appSettings.json with a Dsn key with the DSN value from Sentry. Optionally add a Debug: true value to enable debug mode.
  "Sentry": {
    "Dsn": "https://EXAMPLEDSNREPLACEWITHREALDSNHERE@o8854.ingest.sentry.io/55333455",
    "Debug": true
  },
  1. Configure Sentry in the Program.cs file. Something like the following:
            bool ShouldFilterException(Sentry.SentryEvent ev)
            {
                if (ev.Exception == null)
                    return false;

                if (ev.Exception.Message.IndexOf("controller for path", StringComparison.OrdinalIgnoreCase) >= 0)
                    return true;

                return false;
            }


            if (isDevelopment)
            {
                //Development configuration can be addded here, like local logging.
                return Host.CreateDefaultBuilder(args)
                    .ConfigureCmsDefaults()
                    .ConfigureAppConfiguration((ctx, builder) => {
                        builder.AddConfiguration(_configuration);
                    })
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder
                            .UseSentry(op =>
                            {
                                op.BeforeSend = (ev) =>
                                {
                                    if (ShouldFilterException(ev))
                                        return null;

                                        return ev;
                                };
                            })
                            .UseStartup<Startup>();
                    });
            }
            else
            {
                return Host.CreateDefaultBuilder(args)
                    .ConfigureCmsDefaults()
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder
                            .UseSentry(op =>
                            {
                                op.BeforeSend = (ev) =>
                                {
                                    if (ShouldFilterException(ev))
                                        return null;

                                    return ev;
                                };
                            })
                            .UseStartup<Startup>();
                    });
            }
        }

For CMS 11 / or pre-core version of .NET:

  1. Install Sentry.AspNet nuget package
  2. Add the sentry:Dsn and sentry:Environment application settings. You can use the project's existing DSN.
  3. Update the global.asax.cs file:
        private static IDisposable _sentry = null;

        protected void Application_Start()
        {
            var dsn = ConfigurationManager.AppSettings["sentry:Dsn"];
            if (!string.IsNullOrEmpty(dsn))
            {
                _sentry = SentrySdk.Init(config =>
                {
                    config.Dsn = dsn;
                    config.Environment = ConfigurationManager.AppSettings["sentry:Environment"];
                    // Filter "controller for path not found" (404) errors
                    config.BeforeSend = sentryEvent =>
                    {
                        if (sentryEvent.Exception != null
                            && !string.IsNullOrEmpty(sentryEvent.Exception.Message)
                            && sentryEvent.Exception.Message.IndexOf("controller for path", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            return null;
                        }

                        return sentryEvent;
                    };
                    config.AddAspNet(Sentry.Extensibility.RequestSize.Medium);
                });
            }
        }

        protected void Application_Error()
        {
            var exception = Server.GetLastError();
            SentrySdk.CaptureException(exception);
        }

        protected void Application_End()
        {
            _sentry?.Dispose();
        }

Add the sentry:Dsn and sentry:Environment values in the appSettings of the web.config.

NOTE: In some cases, Application_Error and Application_End may need to be overrides.


Additional Posts

For Episerver - Blend.Sentry

Quick Episerver/Sentry integration. Installation is a 3 step process:

  1. Install the Blend.Sentry nuget package
  2. Add the following value to your appSettings with your Sentry DSN:
     <add key="sentry:Dsn" value="https://XXXX@sentry.io/123456789"/>

Configuration

If you'd like to disable Sentry for local development or a QA server, you can either remove the sentry:Dsn entry from your appSettings, or add the following:

     <add key="sentry:Disabled" value="True"/>

Setting this value to False does nothing.

If you'd like to track pages that take too long to render, you can include the TimeTrackingHttpModule module in your http modules:

	<system.webServer>
		<!-- ...Other modules... -->
		<add name="SentryPageTimeTracking" type="Blend.Sentry.TimeTrackingHttpModule, Blend.Sentry" />
	</system.webServer>

And configure how long a page must take to render to be reported:

	<add key="sentry:ReportServerResponseOverMs" value="1000"/> <!-- Log any page that takes longer than 1 second to render -->

Testing Exception Tracking

If Sentry is configurd and enabled, there will be a route registered for a controller to throw an exception. Hit /sentry-error-test-exception to throw a SentryTestException test exception.

To disable this route, set sentry:TestRouteDisabled to true in the appSettings:

     <add key="sentry:TestRouteDisabled" value="True"/>

Logging your own Exceptions

If you're catching an exception, but would still like to log it (or log other messages), use ILogger:

    try
    {
        throw new InvalidOperationException("ThrowError method called");
    }
    catch (Exception ex)
    {
        // You must install Blend.Sentry into the project to use this. 
        // ILogger is in the Blend.Sentry namespace.
        var logger = ServiceLocator.Current.GetInstance<ILogger>();
        logger.LogException(ex);
    }

Logging Log Exceptions

If logging fails for some reason, the exception is caught and can be handled by setting the OnLoggingException static property on the SentryLogger class.

     SentryLogger.OnLoggingException = (ex) => { Console.Error.WriteLine(ex.Message); }

Comments