|
| 1 | +using NLog; |
| 2 | +using NLog.Config; |
| 3 | +using NLog.Targets; |
| 4 | +using NLog.Web; |
| 5 | +using Sentry.NLog; |
| 6 | + |
| 7 | +// Configure NLog to send logs to Sentry. This only adds the Sentry target: the SDK is initialized by UseSentry below. |
| 8 | +var sentryTarget = new SentryTarget(new SentryNLogOptions |
| 9 | +{ |
| 10 | + // Warn and higher are added as breadcrumbs (default is Info) |
| 11 | + MinimumBreadcrumbLevel = NLog.LogLevel.Warn, |
| 12 | + // Error and higher are sent as events (default is Error) |
| 13 | + MinimumEventLevel = NLog.LogLevel.Error, |
| 14 | +}); |
| 15 | + |
| 16 | +var nlogConfig = new LoggingConfiguration(); |
| 17 | +nlogConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, new ColoredConsoleTarget("console")); |
| 18 | +// Every entry that reaches the Sentry target is sent as a structured log, so this rule sets the minimum level for logs. |
| 19 | +// Info and higher are sent as logs. Breadcrumbs and events can only use entries that pass this rule. |
| 20 | +nlogConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, sentryTarget); |
| 21 | +LogManager.Configuration = nlogConfig; |
| 22 | + |
| 23 | +var builder = WebApplication.CreateBuilder(args); |
| 24 | + |
| 25 | +// Send ILogger entries through NLog. ReplaceLoggerFactory stops the ILogger providers that UseSentry adds from also |
| 26 | +// capturing every entry, so each one reaches Sentry once, through the NLog target, whatever order these calls are in. |
| 27 | +builder.Host.UseNLog(new NLogAspNetCoreOptions { ReplaceLoggerFactory = true }); |
| 28 | + |
| 29 | +builder.UseSentry(options => |
| 30 | +{ |
| 31 | +#if !SENTRY_DSN_DEFINED_IN_ENV |
| 32 | + // A DSN is required. You can set here in code, or you can set it in the SENTRY_DSN environment variable. |
| 33 | + // See https://docs.sentry.io/product/sentry-basics/dsn-explainer/ |
| 34 | + options.Dsn = SamplesShared.Dsn; |
| 35 | +#else |
| 36 | + options.Dsn = EnvironmentVariables.Dsn; |
| 37 | +#endif |
| 38 | +}); |
| 39 | + |
| 40 | +var app = builder.Build(); |
| 41 | + |
| 42 | +app.MapGet("/", (ILogger<Program> logger) => |
| 43 | +{ |
| 44 | + logger.LogDebug("Below the Sentry rule's minimum level, so not sent to Sentry"); |
| 45 | + logger.LogInformation("Sent as a log"); |
| 46 | + logger.LogWarning("Sent as a log and added as a breadcrumb"); |
| 47 | + logger.LogError("Sent as a log and as an event, which includes the breadcrumb above"); |
| 48 | + return "Logged through ILogger at each level. Check Sentry for the logs and the event."; |
| 49 | +}); |
| 50 | + |
| 51 | +app.MapGet("/throw", () => { throw new Exception("An exception thrown from the ASP.NET Core pipeline"); }); |
| 52 | + |
| 53 | +app.Run(); |
| 54 | + |
| 55 | +LogManager.Shutdown(); |
0 commit comments