Skip to content
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Features

- Experimental _Structured Logs_:
- Add integration for `Serilog` ([#4462](https://github.com/getsentry/sentry-dotnet/pull/4462))
- Redesign SDK Logger APIs to allow usage of `params` ([#4451](https://github.com/getsentry/sentry-dotnet/pull/4451))
- Shorten the `key` names of `Microsoft.Extensions.Logging` attributes ([#4450](https://github.com/getsentry/sentry-dotnet/pull/4450))

Expand Down
2 changes: 2 additions & 0 deletions samples/Sentry.Samples.Serilog/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ private static void Main()
// Error and higher is sent as event (default is Error)
options.MinimumEventLevel = LogEventLevel.Error;
options.AttachStacktrace = true;
// send structured logs to Sentry
options.Experimental.EnableLogs = true;
// send PII like the username of the user logged in to the device
options.SendDefaultPii = true;
// Optional Serilog text formatter used to format LogEvent to string. If TextFormatter is set, FormatProvider is ignored.
Expand Down
14 changes: 14 additions & 0 deletions src/Sentry.Serilog/LogLevelExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,18 @@ public static BreadcrumbLevel ToBreadcrumbLevel(this LogEventLevel level)
_ => (BreadcrumbLevel)level
};
}

public static SentryLogLevel ToSentryLogLevel(this LogEventLevel level)
{
return level switch
{
LogEventLevel.Verbose => SentryLogLevel.Trace,
LogEventLevel.Debug => SentryLogLevel.Debug,
LogEventLevel.Information => SentryLogLevel.Info,
LogEventLevel.Warning => SentryLogLevel.Warning,
LogEventLevel.Error => SentryLogLevel.Error,
LogEventLevel.Fatal => SentryLogLevel.Fatal,
_ => (SentryLogLevel)level,
};
}
}
104 changes: 104 additions & 0 deletions src/Sentry.Serilog/SentrySink.Structured.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using Sentry.Internal.Extensions;
using Serilog.Parsing;

namespace Sentry.Serilog;

internal sealed partial class SentrySink
{
private void CaptureStructuredLog(IHub hub, LogEvent logEvent, string formatted, string? template)
{
var traceHeader = hub.GetTraceHeader() ?? SentryTraceHeader.Empty;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the ParentSpanId required in the protocol for StructuredLogging? An empty SpanId probably isn't that useful otherwise eh?

Copy link
Member Author

@Flash0ver Flash0ver Aug 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No ... it's an optional "Default Attribute" ... the trace_id is required.

Oops ... I made this mistake in the Sentry-SDK and Microsoft.Extensions.Logging integrations, too.

I'll create a follow-up PR to fix this issue in all integrations.

GetStructuredLoggingParametersAndAttributes(logEvent, out var parameters, out var attributes);

SentryLog log = new(logEvent.Timestamp, traceHeader.TraceId, logEvent.Level.ToSentryLogLevel(), formatted)
{
Template = template,
Parameters = parameters,
ParentSpanId = traceHeader.SpanId,
};

log.SetDefaultAttributes(_options, Sdk);

foreach (var attribute in attributes)
{
log.SetAttribute(attribute.Key, attribute.Value);
}

hub.Logger.CaptureLog(log);
}

private static void GetStructuredLoggingParametersAndAttributes(LogEvent logEvent, out ImmutableArray<KeyValuePair<string, object>> parameters, out List<KeyValuePair<string, object>> attributes)
{
var propertyNames = new HashSet<string>();
foreach (var token in logEvent.MessageTemplate.Tokens)
{
if (token is PropertyToken property)
{
propertyNames.Add(property.PropertyName);
}
}

var @params = ImmutableArray.CreateBuilder<KeyValuePair<string, object>>();
attributes = new List<KeyValuePair<string, object>>();

foreach (var property in logEvent.Properties)
{
if (propertyNames.Contains(property.Key))
{
foreach (var parameter in GetLogEventProperties(property))
{
@params.Add(parameter);
}
}
else
{
foreach (var attribute in GetLogEventProperties(property))
{
attributes.Add(new KeyValuePair<string, object>($"property.{attribute.Key}", attribute.Value));
}
}
}

parameters = @params.DrainToImmutable();
return;

static IEnumerable<KeyValuePair<string, object>> GetLogEventProperties(KeyValuePair<string, LogEventPropertyValue> property)
{
if (property.Value is ScalarValue scalarValue)
{
if (scalarValue.Value is not null)
{
yield return new KeyValuePair<string, object>(property.Key, scalarValue.Value);
}
}
else if (property.Value is SequenceValue sequenceValue)
{
if (sequenceValue.Elements.Count != 0)
{
yield return new KeyValuePair<string, object>(property.Key, sequenceValue.ToString());
}
}
else if (property.Value is DictionaryValue dictionaryValue)
{
if (dictionaryValue.Elements.Count != 0)
{
yield return new KeyValuePair<string, object>(property.Key, dictionaryValue.ToString());
}
}
else if (property.Value is StructureValue structureValue)
{
foreach (var prop in structureValue.Properties)
{
if (LogEventProperty.IsValidName(prop.Name))
{
yield return new KeyValuePair<string, object>($"{property.Key}.{prop.Name}", prop.Value.ToString());
}
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Inconsistent Structure Handling in Logging

The GetLogEventProperties method handles StructureValue inconsistently with other complex types like SequenceValue and DictionaryValue. It flattens structure properties into multiple key-value pairs using dot notation, rather than capturing the entire structure as a single string-represented value. This causes incorrect structured logging and test failures.

Fix in Cursor Fix in Web

else if (!property.Value.IsNull())
{
yield return new KeyValuePair<string, object>(property.Key, property.Value);
}
}
}
}
49 changes: 29 additions & 20 deletions src/Sentry.Serilog/SentrySink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,20 @@ namespace Sentry.Serilog;
/// </summary>
/// <inheritdoc cref="IDisposable" />
/// <inheritdoc cref="ILogEventSink" />
internal sealed class SentrySink : ILogEventSink, IDisposable
internal sealed partial class SentrySink : ILogEventSink, IDisposable
{
private readonly IDisposable? _sdkDisposable;
private readonly SentrySerilogOptions _options;

internal static readonly SdkVersion NameAndVersion
= typeof(SentrySink).Assembly.GetNameAndVersion();

private static readonly SdkVersion Sdk = new()
{
Name = SdkName,
Version = NameAndVersion.Version,
};

/// <summary>
/// Serilog SDK name.
/// </summary>
Expand Down Expand Up @@ -122,30 +128,33 @@ private void InnerEmit(LogEvent logEvent)
}
}

if (logEvent.Level < _options.MinimumBreadcrumbLevel)
if (logEvent.Level >= _options.MinimumBreadcrumbLevel)
{
return;
Dictionary<string, string>? data = null;
if (exception != null && !string.IsNullOrWhiteSpace(formatted))
{
// Exception.Message won't be used as Breadcrumb message
// Avoid losing it by adding as data:
data = new Dictionary<string, string>
{
{ "exception_message", exception.Message }
};
}

hub.AddBreadcrumb(
_clock,
string.IsNullOrWhiteSpace(formatted)
? exception?.Message ?? ""
: formatted,
context,
data: data,
level: logEvent.Level.ToBreadcrumbLevel());
}

Dictionary<string, string>? data = null;
if (exception != null && !string.IsNullOrWhiteSpace(formatted))
if (_options.Experimental.EnableLogs)
{
// Exception.Message won't be used as Breadcrumb message
// Avoid losing it by adding as data:
data = new Dictionary<string, string>
{
{"exception_message", exception.Message}
};
CaptureStructuredLog(hub, logEvent, formatted, template);
}

hub.AddBreadcrumb(
_clock,
string.IsNullOrWhiteSpace(formatted)
? exception?.Message ?? ""
: formatted,
context,
data: data,
level: logEvent.Level.ToBreadcrumbLevel());
}

private static bool IsSentryContext(string context) =>
Expand Down
43 changes: 32 additions & 11 deletions src/Sentry.Serilog/SentrySinkExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ public static class SentrySinkExtensions
/// </summary>
/// <param name="loggerConfiguration">The logger configuration .<seealso cref="LoggerSinkConfiguration"/></param>
/// <param name="dsn">The Sentry DSN (required). <seealso cref="SentryOptions.Dsn"/></param>
/// <param name="minimumEventLevel">Minimum log level to send an event. <seealso cref="SentrySerilogOptions.MinimumEventLevel"/></param>
/// <param name="minimumBreadcrumbLevel">Minimum log level to record a breadcrumb. <seealso cref="SentrySerilogOptions.MinimumBreadcrumbLevel"/></param>
/// <param name="minimumEventLevel">Minimum log level to send an event. <seealso cref="SentrySerilogOptions.MinimumEventLevel"/></param>
/// <param name="formatProvider">The Serilog format provider. <seealso cref="IFormatProvider"/></param>
/// <param name="textFormatter">The Serilog text formatter. <seealso cref="ITextFormatter"/></param>
/// <param name="sendDefaultPii">Whether to include default Personal Identifiable information. <seealso cref="SentryOptions.SendDefaultPii"/></param>
Expand All @@ -35,6 +35,7 @@ public static class SentrySinkExtensions
/// <param name="reportAssembliesMode">What mode to use for reporting referenced assemblies in each event sent to sentry. Defaults to <see cref="Sentry.ReportAssembliesMode.Version"/></param>
/// <param name="deduplicateMode">What modes to use for event automatic de-duplication. <seealso cref="SentryOptions.DeduplicateMode"/></param>
/// <param name="defaultTags">Default tags to add to all events. <seealso cref="SentryOptions.DefaultTags"/></param>
/// <param name="experimentalEnableLogs">Whether to send structured logs. <seealso cref="SentryOptions.SentryExperimentalOptions.EnableLogs"/></param>
/// <returns><see cref="LoggerConfiguration"/></returns>
/// <example>This sample shows how each item may be set from within a configuration file:
/// <code>
Expand All @@ -50,7 +51,7 @@ public static class SentrySinkExtensions
/// "dsn": "https://[email protected]",
/// "minimumBreadcrumbLevel": "Verbose",
/// "minimumEventLevel": "Error",
/// "outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}"///
/// "outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}",
/// "sendDefaultPii": false,
/// "isEnvironmentUser": false,
/// "serverName": "MyServerName",
Expand All @@ -71,7 +72,8 @@ public static class SentrySinkExtensions
/// "defaultTags": {
/// "key-1", "value-1",
/// "key-2", "value-2"
/// }
/// },
/// "experimentalEnableLogs": true
/// }
/// }
/// ]
Expand Down Expand Up @@ -103,7 +105,8 @@ public static LoggerConfiguration Sentry(
SentryLevel? diagnosticLevel = null,
ReportAssembliesMode? reportAssembliesMode = null,
DeduplicateMode? deduplicateMode = null,
Dictionary<string, string>? defaultTags = null)
Dictionary<string, string>? defaultTags = null,
bool? experimentalEnableLogs = null)
{
return loggerConfiguration.Sentry(o => ConfigureSentrySerilogOptions(o,
dsn,
Expand All @@ -128,7 +131,8 @@ public static LoggerConfiguration Sentry(
diagnosticLevel,
reportAssembliesMode,
deduplicateMode,
defaultTags));
defaultTags,
experimentalEnableLogs));
}

/// <summary>
Expand All @@ -143,6 +147,7 @@ public static LoggerConfiguration Sentry(
/// <param name="minimumBreadcrumbLevel">Minimum log level to record a breadcrumb. <seealso cref="SentrySerilogOptions.MinimumBreadcrumbLevel"/></param>
/// <param name="formatProvider">The Serilog format provider. <seealso cref="IFormatProvider"/></param>
/// <param name="textFormatter">The Serilog text formatter. <seealso cref="ITextFormatter"/></param>
/// <param name="experimentalEnableLogs">Whether to send structured logs. <seealso cref="SentryOptions.SentryExperimentalOptions.EnableLogs"/></param>
/// <returns><see cref="LoggerConfiguration"/></returns>
/// <example>This sample shows how each item may be set from within a configuration file:
/// <code>
Expand All @@ -157,7 +162,8 @@ public static LoggerConfiguration Sentry(
/// "Args": {
/// "minimumEventLevel": "Error",
/// "minimumBreadcrumbLevel": "Verbose",
/// "outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}"///
/// "outputTemplate": "{Timestamp:o} [{Level:u3}] ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}",
/// "experimentalEnableLogs": true
/// }
/// }
/// ]
Expand All @@ -170,15 +176,17 @@ public static LoggerConfiguration Sentry(
LogEventLevel? minimumEventLevel = null,
LogEventLevel? minimumBreadcrumbLevel = null,
IFormatProvider? formatProvider = null,
ITextFormatter? textFormatter = null
ITextFormatter? textFormatter = null,
bool? experimentalEnableLogs = null
)
{
return loggerConfiguration.Sentry(o => ConfigureSentrySerilogOptions(o,
null,
minimumEventLevel,
minimumBreadcrumbLevel,
formatProvider,
textFormatter));
textFormatter,
experimentalEnableLogs: experimentalEnableLogs));
}

internal static void ConfigureSentrySerilogOptions(
Expand All @@ -205,7 +213,8 @@ internal static void ConfigureSentrySerilogOptions(
SentryLevel? diagnosticLevel = null,
ReportAssembliesMode? reportAssembliesMode = null,
DeduplicateMode? deduplicateMode = null,
Dictionary<string, string>? defaultTags = null)
Dictionary<string, string>? defaultTags = null,
bool? experimentalEnableLogs = null)
{
if (dsn is not null)
{
Expand Down Expand Up @@ -317,6 +326,11 @@ internal static void ConfigureSentrySerilogOptions(
sentrySerilogOptions.DeduplicateMode = deduplicateMode.Value;
}

if (experimentalEnableLogs.HasValue)
{
sentrySerilogOptions.Experimental.EnableLogs = experimentalEnableLogs.Value;
}

// Serilog-specific items
sentrySerilogOptions.InitializeSdk = dsn is not null; // Inferred from the Sentry overload that is used
if (defaultTags?.Count > 0)
Expand Down Expand Up @@ -354,7 +368,14 @@ public static LoggerConfiguration Sentry(
sdkDisposable = SentrySdk.Init(options);
}

var minimumOverall = (LogEventLevel)Math.Min((int)options.MinimumBreadcrumbLevel, (int)options.MinimumEventLevel);
return loggerConfiguration.Sink(new SentrySink(options, sdkDisposable), minimumOverall);
if (options.Experimental.EnableLogs)
{
return loggerConfiguration.Sink(new SentrySink(options, sdkDisposable));
}
else
{
var minimumOverall = (LogEventLevel)Math.Min((int)options.MinimumBreadcrumbLevel, (int)options.MinimumEventLevel);
return loggerConfiguration.Sink(new SentrySink(options, sdkDisposable), minimumOverall);
}
}
}
1 change: 1 addition & 0 deletions src/Sentry/SentryLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace Sentry;
/// <para>This API is experimental and it may change in the future.</para>
/// </summary>
[Experimental(DiagnosticId.ExperimentalFeature)]
[DebuggerDisplay(@"SentryLog \{ Level = {Level}, Message = '{Message}' \}")]
public sealed class SentryLog
{
private readonly Dictionary<string, SentryAttribute> _attributes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace Serilog
public static class SentrySinkExtensions
{
public static Serilog.LoggerConfiguration Sentry(this Serilog.Configuration.LoggerSinkConfiguration loggerConfiguration, System.Action<Sentry.Serilog.SentrySerilogOptions> configureOptions) { }
public static Serilog.LoggerConfiguration Sentry(this Serilog.Configuration.LoggerSinkConfiguration loggerConfiguration, Serilog.Events.LogEventLevel? minimumEventLevel = default, Serilog.Events.LogEventLevel? minimumBreadcrumbLevel = default, System.IFormatProvider? formatProvider = null, Serilog.Formatting.ITextFormatter? textFormatter = null) { }
public static Serilog.LoggerConfiguration Sentry(this Serilog.Configuration.LoggerSinkConfiguration loggerConfiguration, Serilog.Events.LogEventLevel? minimumEventLevel = default, Serilog.Events.LogEventLevel? minimumBreadcrumbLevel = default, System.IFormatProvider? formatProvider = null, Serilog.Formatting.ITextFormatter? textFormatter = null, bool? experimentalEnableLogs = default) { }
public static Serilog.LoggerConfiguration Sentry(
this Serilog.Configuration.LoggerSinkConfiguration loggerConfiguration,
string dsn,
Expand All @@ -46,6 +46,7 @@ namespace Serilog
Sentry.SentryLevel? diagnosticLevel = default,
Sentry.ReportAssembliesMode? reportAssembliesMode = default,
Sentry.DeduplicateMode? deduplicateMode = default,
System.Collections.Generic.Dictionary<string, string>? defaultTags = null) { }
System.Collections.Generic.Dictionary<string, string>? defaultTags = null,
bool? experimentalEnableLogs = default) { }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace Serilog
public static class SentrySinkExtensions
{
public static Serilog.LoggerConfiguration Sentry(this Serilog.Configuration.LoggerSinkConfiguration loggerConfiguration, System.Action<Sentry.Serilog.SentrySerilogOptions> configureOptions) { }
public static Serilog.LoggerConfiguration Sentry(this Serilog.Configuration.LoggerSinkConfiguration loggerConfiguration, Serilog.Events.LogEventLevel? minimumEventLevel = default, Serilog.Events.LogEventLevel? minimumBreadcrumbLevel = default, System.IFormatProvider? formatProvider = null, Serilog.Formatting.ITextFormatter? textFormatter = null) { }
public static Serilog.LoggerConfiguration Sentry(this Serilog.Configuration.LoggerSinkConfiguration loggerConfiguration, Serilog.Events.LogEventLevel? minimumEventLevel = default, Serilog.Events.LogEventLevel? minimumBreadcrumbLevel = default, System.IFormatProvider? formatProvider = null, Serilog.Formatting.ITextFormatter? textFormatter = null, bool? experimentalEnableLogs = default) { }
public static Serilog.LoggerConfiguration Sentry(
this Serilog.Configuration.LoggerSinkConfiguration loggerConfiguration,
string dsn,
Expand All @@ -46,6 +46,7 @@ namespace Serilog
Sentry.SentryLevel? diagnosticLevel = default,
Sentry.ReportAssembliesMode? reportAssembliesMode = default,
Sentry.DeduplicateMode? deduplicateMode = default,
System.Collections.Generic.Dictionary<string, string>? defaultTags = null) { }
System.Collections.Generic.Dictionary<string, string>? defaultTags = null,
bool? experimentalEnableLogs = default) { }
}
}
Loading
Loading