Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
90 commits
Select commit Hold shift + click to select a range
0add668
feat(logs): initial experiment
Flash0ver Apr 30, 2025
db7d558
feat(logs): basic Logger Module API shape
Flash0ver Apr 30, 2025
d96b092
style(logs): consolidate
Flash0ver May 5, 2025
2958a47
ref(logs): remove generic WriteSerializable overload
Flash0ver May 5, 2025
a63371b
ref(logs): consolidate experimental Diagnostic-ID
Flash0ver May 5, 2025
d8d2567
feat(logs): add experimental options
Flash0ver May 7, 2025
fefd24c
Merge branch 'main' into feat/logs-initial-api
Flash0ver May 7, 2025
165996a
ref(logs): remove custom polyfills now provided through Polyfill
Flash0ver May 7, 2025
32e7e25
Format code
getsentry-bot May 7, 2025
fc88722
Merge branch 'feat/logs-initial-api' of https://github.com/getsentry/…
Flash0ver May 7, 2025
2ba87e4
ref(logs): move types out of Experimental namespace
Flash0ver May 7, 2025
0f1d4a4
feat(logs): change 'integer' from Int32 to Int64
Flash0ver May 7, 2025
8dec5d5
ref(logs): refine API surface area
Flash0ver May 8, 2025
a664f7e
ref(logs): match SeverityLevel to OTel spec
Flash0ver May 8, 2025
96693d0
ref(logs): rename SentrySeverity to LogSeverityLevel
Flash0ver May 8, 2025
83964cf
Format code
getsentry-bot May 8, 2025
dadc69b
ref(logs): hide underlying Dictionary`2 for Attributes
Flash0ver May 9, 2025
c91cdde
ref(logs): restructure attributes
Flash0ver May 9, 2025
0740c3b
ref(logs): extract TraceId and ParentSpanId methods
Flash0ver May 9, 2025
eee06bf
ref(logs): remove `SentryOptions.LogsSampleRate`
Flash0ver May 12, 2025
8c61d8b
feat(logs): support ISystemClock abstraction
Flash0ver May 12, 2025
80683ae
ref(logs): disambiguate SentryLogger names
Flash0ver May 12, 2025
cb20118
ref(logs): consolidate names of Log-Methods
Flash0ver May 12, 2025
2cb306f
ref(logs): rename LogSeverityLevel to SentryLogLevel
Flash0ver May 12, 2025
dcc0ec1
ref(logs): re-rename new logger type
Flash0ver May 13, 2025
58dce74
ref(logs): move Logger instances to Hubs
Flash0ver May 14, 2025
f2e1ba2
test(logs): add tests
Flash0ver May 14, 2025
0220015
Merge branch 'main' into feat/logs-initial-api
Flash0ver May 14, 2025
6822b23
Format code
getsentry-bot May 14, 2025
dd39fae
fix(logs): incorrectly serializing attributes
Flash0ver May 14, 2025
6eb5b9b
fix(logs): do not capture log when template/parameters are invalid
Flash0ver May 14, 2025
69c05b8
fix(logs): do not capture log on user callback exceptions
Flash0ver May 14, 2025
430cf82
ref(logs): move new public types to root namespace
Flash0ver May 14, 2025
31a8f1f
ref(logs): rework sample
Flash0ver May 14, 2025
2ae4476
ref(logs): ensure that DisabledHub dues not capture logs
Flash0ver May 14, 2025
69678ce
ref(logs): allow out-of-range Log-Level
Flash0ver May 14, 2025
97995a8
docs(logs): add XML comments indicating that logs will be ignored on …
Flash0ver May 14, 2025
fbe747d
docs(logs): add to changelog
Flash0ver May 15, 2025
64adf33
fix(logs): add to Bindable-Options
Flash0ver May 15, 2025
cdfa901
fix(logs): add to ApiApprovalTests
Flash0ver May 15, 2025
d2ac53b
test(logs): add missing net48 ApiApproval
Flash0ver May 15, 2025
4011ba6
test(logs): fix line endings on Windows
Flash0ver May 15, 2025
4ae82d0
Update src/Sentry/Protocol/Envelopes/Envelope.cs
Flash0ver May 15, 2025
bc1c465
Update SentryLog.cs
Flash0ver May 15, 2025
79fb190
test(logs): fix floating-point ToString expectation for .NET Framework
Flash0ver May 15, 2025
b4e80f4
ref(logs): remove some using declarations
Flash0ver May 15, 2025
b21adef
test(ci): trying to work around floating-point formatter on .NET Fram…
Flash0ver May 15, 2025
0032858
test(logs): skip failing tests on Mono (non-Windows)
Flash0ver May 15, 2025
a9769f8
test(log): fix Skip.If missing SkippableFact
Flash0ver May 15, 2025
9a51033
try: fix floating-point formatting on Windows
Flash0ver May 15, 2025
9a09832
Merge branch 'main' into feat/logs-initial-api
Flash0ver May 21, 2025
f133118
Merge branch 'main' into feat/logs-initial-api
Flash0ver Jun 3, 2025
72c9a93
ref: make SentryStructuredLogger abstract
Flash0ver Jun 4, 2025
c97f4ad
docs: add comment to sample usage of SetBeforeSendLog
Flash0ver Jun 5, 2025
a9eea90
ref: clarify intent of usages of Debug.Assert
Flash0ver Jun 5, 2025
8bd0ed2
docs: improve XML comments
Flash0ver Jun 5, 2025
51892de
test: range of Severity-Number specification
Flash0ver Jun 5, 2025
acc8995
test: GetValuesAsUnderlyingType of the new enum
Flash0ver Jun 5, 2025
6bd4c96
ref: move Log options to Experimental section
Flash0ver Jun 5, 2025
f673d1e
ref: move Logger to Experimental section of SDK
Flash0ver Jun 5, 2025
daafd7f
test: add Hub tests
Flash0ver Jun 5, 2025
62ee5d5
Merge branch 'feat/logs' into feat/logs-initial-api
Flash0ver Jun 6, 2025
6a54203
test: update verified public API
Flash0ver Jun 6, 2025
479cab8
docs: update CHANGELOG.md
Flash0ver Jun 6, 2025
97a87f8
Merge branch 'main' into feat/logs-initial-api
jamescrosswell Jun 9, 2025
0467449
Merge branch 'feat/logs' into feat/logs-initial-api
Flash0ver Jun 16, 2025
54062d2
ref: reuse Disabled-Instance when Structured-Logging is not enabled
Flash0ver Jun 16, 2025
7107bce
ref: remove Enabled-checks on Default-Logger
Flash0ver Jun 16, 2025
c0a1cd5
ref: rename DisabledSentryStructuredLogger to NoOpSentryStructuredLogger
Flash0ver Jun 16, 2025
45b8687
ref: make `BindableSentryOptions.Experimental` internal
Flash0ver Jun 16, 2025
3192534
Revert "ref: make `BindableSentryOptions.Experimental` internal"
Flash0ver Jun 16, 2025
b8bcea6
docs: Update CHANGELOG.md
Flash0ver Jun 16, 2025
d4c82a2
Revert "ref: rename DisabledSentryStructuredLogger to NoOpSentryStruc…
Flash0ver Jun 18, 2025
9193a96
ref: replace use of ScopeManager with TraceHeader
Flash0ver Jun 18, 2025
7cb4043
test: remove Skip as we no longer test net48 against non-Windows
Flash0ver Jun 18, 2025
e3ca5b5
feat: support more numeric types
Flash0ver Jun 20, 2025
afb135e
feat: support char attributes
Flash0ver Jun 20, 2025
7f675aa
fix: build error targeting .NET Standard 2.0 and .NET Framework
Flash0ver Jun 20, 2025
750a388
fix: exception when passing null as message parameter
Flash0ver Jun 20, 2025
9f62d3b
test: add Attributes-To-Json test
Flash0ver Jun 20, 2025
5b00c21
fix: missing type on .NET Framework
Flash0ver Jun 24, 2025
6d17918
feat: support Attribute-Types from spec
Flash0ver Jun 24, 2025
7e2c57b
ref: clarify internal identifiers
Flash0ver Jun 24, 2025
7115c42
test: update approved API
Flash0ver Jun 24, 2025
cd5246b
test: fix incorrect expectation
Flash0ver Jun 24, 2025
baf5569
Merge branch 'feat/logs' into feat/logs-initial-api
Flash0ver Jun 24, 2025
6e13e95
feat: use "wrapping" SDK's Name and Version
Flash0ver Jun 25, 2025
0a9a3b1
fix: Get-Attribute-API
Flash0ver Jun 25, 2025
934fb36
Merge branch 'feat/logs' into feat/logs-initial-api
Flash0ver Jun 25, 2025
2c1608e
docs: update CHANGELOG
Flash0ver Jun 25, 2025
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

### Features

- Add experimental support for [Sentry Structured Logging](https://docs.sentry.io/product/explore/logs/) via `SentrySdk.Experimental.Logger` ([#4158](https://github.com/getsentry/sentry-dotnet/pull/4158))

## 5.11.2

### Fixes
Expand Down
20 changes: 20 additions & 0 deletions samples/Sentry.Samples.Console.Basic/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* - Error Monitoring (both handled and unhandled exceptions)
* - Performance Tracing (Transactions / Spans)
* - Release Health (Sessions)
* - Logs
* - MSBuild integration for Source Context (see the csproj)
*
* For more advanced features of the SDK, see Sentry.Samples.Console.Customized.
Expand Down Expand Up @@ -35,6 +36,20 @@

// This option tells Sentry to capture 100% of traces. You still need to start transactions and spans.
options.TracesSampleRate = 1.0;

// This option enables Sentry Logs created via SentrySdk.Logger.
options.Experimental.EnableLogs = true;
options.Experimental.SetBeforeSendLog(static log =>
{
// A demonstration of how you can drop logs based on some attribute they have
if (log.TryGetAttribute("suppress", out var attribute) && attribute is true)
{
return null;
}

// Drop logs with level Info
return log.Level is SentryLogLevel.Info ? null : log;
});
});

// This starts a new transaction and attaches it to the scope.
Expand All @@ -58,6 +73,7 @@ async Task FirstFunction()
var httpClient = new HttpClient(messageHandler, true);
var html = await httpClient.GetStringAsync("https://example.com/");
WriteLine(html);
SentrySdk.Experimental.Logger.LogInfo("HTTP Request completed.");
}

async Task SecondFunction()
Expand All @@ -77,6 +93,8 @@ async Task SecondFunction()
// This is an example of capturing a handled exception.
SentrySdk.CaptureException(exception);
span.Finish(exception);

SentrySdk.Experimental.Logger.LogError("Error with message: {0}", [exception.Message], static log => log.SetAttribute("method", nameof(SecondFunction)));
}

span.Finish();
Expand All @@ -90,6 +108,8 @@ async Task ThirdFunction()
// Simulate doing some work
await Task.Delay(100);

SentrySdk.Experimental.Logger.LogFatal("Crash imminent!", [], static log => log.SetAttribute("suppress", true));

// This is an example of an unhandled exception. It will be captured automatically.
throw new InvalidOperationException("Something happened that crashed the app!");
}
Expand Down
11 changes: 11 additions & 0 deletions src/Sentry/BindableSentryOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ internal partial class BindableSentryOptions
public bool? EnableSpotlight { get; set; }
public string? SpotlightUrl { get; set; }

[Experimental(Infrastructure.DiagnosticId.ExperimentalFeature)]
public BindableSentryExperimentalOptions Experimental { get; set; } = new();

[Experimental(Infrastructure.DiagnosticId.ExperimentalFeature)]
internal sealed class BindableSentryExperimentalOptions
{
public bool? EnableLogs { get; set; }
}

public void ApplyTo(SentryOptions options)
{
options.IsGlobalModeEnabled = IsGlobalModeEnabled ?? options.IsGlobalModeEnabled;
Expand Down Expand Up @@ -100,6 +109,8 @@ public void ApplyTo(SentryOptions options)
options.EnableSpotlight = EnableSpotlight ?? options.EnableSpotlight;
options.SpotlightUrl = SpotlightUrl ?? options.SpotlightUrl;

options.Experimental.EnableLogs = Experimental.EnableLogs ?? options.Experimental.EnableLogs;

#if ANDROID
Android.ApplyTo(options.Android);
Native.ApplyTo(options.Native);
Expand Down
22 changes: 22 additions & 0 deletions src/Sentry/Extensibility/DiagnosticLoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ internal static void LogDebug<TArg, TArg2>(
TArg2 arg2)
=> options.DiagnosticLogger?.LogIfEnabled(SentryLevel.Debug, null, message, arg, arg2);

/// <summary>
/// Log a debug message.
/// </summary>
public static void LogDebug<TArg, TArg2, TArg3>(
this IDiagnosticLogger logger,
string message,
TArg arg,
TArg2 arg2,
TArg3 arg3)
=> logger.LogIfEnabled(SentryLevel.Debug, null, message, arg, arg2, arg3);

/// <summary>
/// Log a debug message.
/// </summary>
Expand Down Expand Up @@ -233,6 +244,17 @@ internal static void LogWarning<TArg, TArg2>(
TArg2 arg2)
=> options.DiagnosticLogger?.LogIfEnabled(SentryLevel.Warning, null, message, arg, arg2);

/// <summary>
/// Log a warning message.
/// </summary>
public static void LogWarning<TArg, TArg2, TArg3>(
this IDiagnosticLogger logger,
string message,
TArg arg,
TArg2 arg2,
TArg3 arg3)
=> logger.LogIfEnabled(SentryLevel.Warning, null, message, arg, arg2, arg3);

/// <summary>
/// Log a warning message.
/// </summary>
Expand Down
7 changes: 7 additions & 0 deletions src/Sentry/Extensibility/DisabledHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -254,4 +254,11 @@ public void CaptureUserFeedback(UserFeedback userFeedback)
/// No-Op.
/// </summary>
public SentryId LastEventId => SentryId.Empty;

/// <summary>
/// Disabled Logger.
/// <para>This API is experimental and it may change in the future.</para>
/// </summary>
[Experimental(Infrastructure.DiagnosticId.ExperimentalFeature)]
public SentryStructuredLogger Logger => DisabledSentryStructuredLogger.Instance;
}
7 changes: 7 additions & 0 deletions src/Sentry/Extensibility/HubAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ private HubAdapter() { }
/// </summary>
public SentryId LastEventId { [DebuggerStepThrough] get => SentrySdk.LastEventId; }

/// <summary>
/// Forwards the call to <see cref="SentrySdk"/>.
/// <para>This API is experimental and it may change in the future.</para>
/// </summary>
[Experimental(DiagnosticId.ExperimentalFeature)]
public SentryStructuredLogger Logger { [DebuggerStepThrough] get => SentrySdk.Experimental.Logger; }

/// <summary>
/// Forwards the call to <see cref="SentrySdk"/>.
/// </summary>
Expand Down
12 changes: 12 additions & 0 deletions src/Sentry/HubExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -259,4 +259,16 @@ internal static ITransactionTracer StartTransaction(
var transaction = hub.GetTransaction();
return transaction?.IsSampled == true ? transaction : null;
}

internal static Scope? GetScope(this IHub hub)
{
if (hub is Hub fullHub)
{
return fullHub.ScopeManager.GetCurrent().Key;
}

Scope? current = null;
hub.ConfigureScope(scope => current = scope);
return current;
}
}
14 changes: 14 additions & 0 deletions src/Sentry/IHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,20 @@ public interface IHub : ISentryClient, ISentryScopeManager
/// </summary>
public SentryId LastEventId { get; }

/// <summary>
/// Creates and sends logs to Sentry.
/// <para>This API is experimental and it may change in the future.</para>
/// </summary>
/// <remarks>
/// Available options:
/// <list type="bullet">
/// <item><see cref="Sentry.SentryOptions.SentryExperimentalOptions.EnableLogs"/></item>
/// <item><see cref="Sentry.SentryOptions.SentryExperimentalOptions.SetBeforeSendLog(System.Func{SentryLog, SentryLog})"/></item>
/// </list>
/// </remarks>
[Experimental(Infrastructure.DiagnosticId.ExperimentalFeature)]
public SentryStructuredLogger Logger { get; }

/// <summary>
/// Starts a transaction.
/// </summary>
Expand Down
2 changes: 0 additions & 2 deletions src/Sentry/Infrastructure/DiagnosticId.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ namespace Sentry.Infrastructure;

internal static class DiagnosticId
{
#if NET5_0_OR_GREATER
/// <summary>
/// Indicates that the feature is experimental and may be subject to change or removal in future versions.
/// </summary>
internal const string ExperimentalFeature = "SENTRY0001";
#endif
}
79 changes: 79 additions & 0 deletions src/Sentry/Internal/DefaultSentryStructuredLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using Sentry.Extensibility;
using Sentry.Infrastructure;
using Sentry.Protocol.Envelopes;

namespace Sentry.Internal;

internal sealed class DefaultSentryStructuredLogger : SentryStructuredLogger
{
private readonly IHub _hub;
private readonly SentryOptions _options;
private readonly ISystemClock _clock;

internal DefaultSentryStructuredLogger(IHub hub, SentryOptions options, ISystemClock clock)
{
Debug.Assert(options is { Experimental.EnableLogs: true });

_hub = hub;
_options = options;
_clock = clock;
}

private protected override void CaptureLog(SentryLogLevel level, string template, object[]? parameters, Action<SentryLog>? configureLog)
{
var timestamp = _clock.GetUtcNow();
var traceHeader = _hub.GetTraceHeader() ?? SentryTraceHeader.Empty;

string message;
try
{
message = string.Format(CultureInfo.InvariantCulture, template, parameters ?? []);
}
catch (FormatException e)
{
_options.DiagnosticLogger?.LogError(e, "Template string does not match the provided argument. The Log will be dropped.");
return;
}

SentryLog log = new(timestamp, traceHeader.TraceId, level, message)
{
Template = template,
Parameters = ImmutableArray.Create(parameters),
ParentSpanId = traceHeader.SpanId,
};

try
{
configureLog?.Invoke(log);
Copy link
Member

Choose a reason for hiding this comment

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

I find it odd that we have this callback to be invoked directly when capturing a log.

What are the use cases that we'll call explicitly: Log(a,b,c,d, (log) => {}) when log contains the fields I anyway just provided to the Log() siuch as a,b,c,d?)

The use case for a callback when the user isn't calling the Log() method directly makes a lot of sense to me, and we have that below with beforeLog but having both is odd.

}
catch (Exception e)
{
_options.DiagnosticLogger?.LogError(e, "The configureLog callback threw an exception. The Log will be dropped.");
return;
}

var scope = _hub.GetScope();
log.SetDefaultAttributes(_options, scope?.Sdk ?? SdkVersion.Instance);

var configuredLog = log;
if (_options.Experimental.BeforeSendLogInternal is { } beforeSendLog)
{
try
{
configuredLog = beforeSendLog.Invoke(log);
}
catch (Exception e)
{
_options.DiagnosticLogger?.LogError(e, "The BeforeSendLog callback threw an exception. The Log will be dropped.");
return;
}
}

if (configuredLog is not null)
{
//TODO: enqueue in Batch-Processor / Background-Worker
// see https://github.com/getsentry/sentry-dotnet/issues/4132
_ = _hub.CaptureEnvelope(Envelope.FromLog(configuredLog));
}
}
}
15 changes: 15 additions & 0 deletions src/Sentry/Internal/DisabledSentryStructuredLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Sentry.Internal;

internal sealed class DisabledSentryStructuredLogger : SentryStructuredLogger
{
internal static DisabledSentryStructuredLogger Instance { get; } = new DisabledSentryStructuredLogger();

internal DisabledSentryStructuredLogger()
{
}

private protected override void CaptureLog(SentryLogLevel level, string template, object[]? parameters, Action<SentryLog>? configureLog)
{
// disabled
}
}
5 changes: 5 additions & 0 deletions src/Sentry/Internal/Hub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ internal Hub(
PushScope();
}

Logger = SentryStructuredLogger.Create(this, options, _clock);

#if MEMORY_DUMP_SUPPORTED
if (options.HeapDumpOptions is not null)
{
Expand Down Expand Up @@ -800,4 +802,7 @@ public void Dispose()
}

public SentryId LastEventId => CurrentScope.LastEventId;

[Experimental(DiagnosticId.ExperimentalFeature)]
public SentryStructuredLogger Logger { get; }
}
16 changes: 16 additions & 0 deletions src/Sentry/Protocol/Envelopes/Envelope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,22 @@ internal static Envelope FromClientReport(ClientReport clientReport)
return new Envelope(header, items);
}

// TODO: This is temporary. We don't expect single log messages to become an envelope by themselves since batching is needed
[Experimental(DiagnosticId.ExperimentalFeature)]
internal static Envelope FromLog(SentryLog log)
{
//TODO: allow batching Sentry logs
//see https://github.com/getsentry/sentry-dotnet/issues/4132
var header = DefaultHeader;

var items = new[]
{
EnvelopeItem.FromLog(log)
};

return new Envelope(header, items);
}

private static async Task<IReadOnlyDictionary<string, object?>> DeserializeHeaderAsync(
Stream stream,
CancellationToken cancellationToken = default)
Expand Down
16 changes: 16 additions & 0 deletions src/Sentry/Protocol/Envelopes/EnvelopeItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public sealed class EnvelopeItem : ISerializable, IDisposable
internal const string TypeValueProfile = "profile";
internal const string TypeValueMetric = "statsd";
internal const string TypeValueCodeLocations = "metric_meta";
internal const string TypeValueLog = "log";

private const string LengthKey = "length";
private const string FileNameKey = "filename";
Expand Down Expand Up @@ -370,6 +371,21 @@ internal static EnvelopeItem FromClientReport(ClientReport report)
return new EnvelopeItem(header, new JsonSerializable(report));
}

[Experimental(Infrastructure.DiagnosticId.ExperimentalFeature)]
internal static EnvelopeItem FromLog(SentryLog log)
{
//TODO: allow batching Sentry logs
//see https://github.com/getsentry/sentry-dotnet/issues/4132
var header = new Dictionary<string, object?>(3, StringComparer.Ordinal)
{
[TypeKey] = TypeValueLog,
["item_count"] = 1,
["content_type"] = "application/vnd.sentry.items.log+json",
};

return new EnvelopeItem(header, new JsonSerializable(log));
}

private static async Task<Dictionary<string, object?>> DeserializeHeaderAsync(
Stream stream,
CancellationToken cancellationToken = default)
Expand Down
Loading
Loading