|
| 1 | +using Serilog.Context; |
| 2 | + |
| 3 | +namespace Sentry.Serilog; |
| 4 | + |
| 5 | +/// <summary> |
| 6 | +/// Sentry event processor that applies properties from the Serilog scope to Sentry events. |
| 7 | +/// </summary> |
| 8 | +internal class SerilogScopeEventProcessor : ISentryEventProcessor |
| 9 | +{ |
| 10 | + private readonly SentryOptions _options; |
| 11 | + |
| 12 | + /// <summary> |
| 13 | + /// This processor extracts properties from the Serilog context and applies these to Sentry events. |
| 14 | + /// </summary> |
| 15 | + public SerilogScopeEventProcessor(SentryOptions options) |
| 16 | + { |
| 17 | + _options = options; |
| 18 | + _options.LogDebug("Initializing Serilog scope event processor."); |
| 19 | + } |
| 20 | + |
| 21 | + /// <inheritdoc cref="ISentryEventProcessor"/> |
| 22 | + public SentryEvent Process(SentryEvent @event) |
| 23 | + { |
| 24 | + _options.LogDebug("Running Serilog scope event processor on: Event {0}", @event.EventId); |
| 25 | + |
| 26 | + // This is a bit of a hack. Serilog doesn't have any hooks that let us inspect the context. We can, however, |
| 27 | + // apply the context to a dummy log event and then copy across the properties from that log event to our Sentry |
| 28 | + // event. |
| 29 | + // See: https://github.com/getsentry/sentry-dotnet/issues/3544#issuecomment-2307884977 |
| 30 | + var enricher = LogContext.Clone(); |
| 31 | + var logEvent = new LogEvent(DateTimeOffset.Now, LogEventLevel.Error, null, MessageTemplate.Empty, []); |
| 32 | + enricher.Enrich(logEvent, new LogEventPropertyFactory()); |
| 33 | + foreach (var (key, value) in logEvent.Properties) |
| 34 | + { |
| 35 | + if (!@event.Tags.ContainsKey(key)) |
| 36 | + { |
| 37 | + // Potentially we could be doing SetData here instead of SetTag. See DefaultSentryScopeStateProcessor. |
| 38 | + @event.SetTag(key, value.ToString()); |
| 39 | + } |
| 40 | + } |
| 41 | + return @event; |
| 42 | + } |
| 43 | + |
| 44 | + private class LogEventPropertyFactory : ILogEventPropertyFactory |
| 45 | + { |
| 46 | + public LogEventProperty CreateProperty(string name, object? value, bool destructureObjects = false) |
| 47 | + { |
| 48 | + var scalarValue = new ScalarValue(value); |
| 49 | + return new LogEventProperty(name, scalarValue); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments