Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
134 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
8d03449
feat(logs): Sentry.Extensions.Logging
Flash0ver May 16, 2025
1bc3a6f
feat(logs): Sentry.AspNetCore
Flash0ver May 16, 2025
7624baa
feat(logs): Sentry.Maui
Flash0ver May 16, 2025
11fe02b
fix(logs): Logging Filter
Flash0ver May 16, 2025
fd532ca
Format code
getsentry-bot May 16, 2025
1fe9cc0
feat(logs): add CHANGELOG entry
Flash0ver May 16, 2025
476cbc3
Merge branch 'feat/logs-microsoft-extensions-logging' of https://gith…
Flash0ver May 16, 2025
9a09832
Merge branch 'main' into feat/logs-initial-api
Flash0ver May 21, 2025
d9ce523
Merge branch 'main' into feat/logs-microsoft-extensions-logging
Flash0ver May 21, 2025
3e6dba5
release: 5.8.0-alpha.0
getsentry-bot May 21, 2025
23934dc
Merge branch 'release/5.8.0-alpha.0' into feat/logs-microsoft-extensi…
May 22, 2025
f133118
Merge branch 'main' into feat/logs-initial-api
Flash0ver Jun 3, 2025
0985a76
Merge branch 'main' into feat/logs-microsoft-extensions-logging
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
f59160b
Merge branch 'feat/logs-initial-api' into feat/logs-microsoft-extensi…
Flash0ver Jun 6, 2025
18a8284
ref: move Log-rerelated Options to Experimental sub-section
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
e592d03
Merge branch 'feat/logs-initial-api' into feat/logs-microsoft-extensi…
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
2b09a79
Merge branch 'feat/logs-initial-api' into feat/logs-microsoft-extensi…
Flash0ver Jun 25, 2025
2950be9
docs: update CHANGELOG
Flash0ver Jun 25, 2025
8d35362
feat(logs): initial API for Sentry Logs (#4158)
Flash0ver Jun 25, 2025
d24d165
feat: add Batch Processor for Logs
Flash0ver Jun 26, 2025
aad0599
test: Batch Processor for Logs
Flash0ver Jun 26, 2025
76fcc1b
docs: Batch Processor for Logs
Flash0ver Jun 26, 2025
2ad33f6
test: fix unavailable API on TargetFramework=net48
Flash0ver Jun 27, 2025
38e1c04
test: run all Logs tests on full framework
Flash0ver Jun 27, 2025
f7a43b8
ref: remove usage of System.Threading.Lock
Flash0ver Jun 27, 2025
e6b0b74
ref: rename members for clarity
Flash0ver Jun 30, 2025
f5b5971
Merge branch 'main' into feat/logs
Flash0ver Jun 30, 2025
a84b78f
Merge branch 'feat/logs' into feat/logs-buffering
Flash0ver Jun 30, 2025
53c90ea
ref: delete Timer-Abstraction and change to System.Threading.Timer
Flash0ver Jul 1, 2025
6580632
ref: delete .ctor only called from tests
Flash0ver Jul 1, 2025
6e2ee9b
ref: switch Buffer-Processor to be lock-free but discarding
Flash0ver Jul 2, 2025
0774709
test: fix BatchBuffer and Tests
Flash0ver Jul 3, 2025
d9ae794
fix: flushing buffer on Timeout
Flash0ver Jul 8, 2025
7e1f5ea
feat: add Backpressure-ClientReport
Flash0ver Jul 10, 2025
365a2fb
ref: make BatchProcessor more resilient
Flash0ver Jul 11, 2025
8b1f716
Merge branch 'main' into feat/logs
Flash0ver Jul 11, 2025
c478391
Format code
getsentry-bot Jul 11, 2025
eeae2ab
Merge branch 'main' into feat/logs
Flash0ver Jul 11, 2025
211beea
Merge branch 'feat/logs' into feat/logs-buffering
Flash0ver Jul 11, 2025
d428163
Merge branch 'feat/logs' into feat/logs-microsoft-extensions-logging
Flash0ver Jul 11, 2025
a936ec6
test: change options to Experimental section
Flash0ver Jul 11, 2025
c699c2d
test: fix on .NET Framework
Flash0ver Jul 11, 2025
ca00162
Merge branch 'feat/logs-microsoft-extensions-logging' into feat/logs-…
Flash0ver Jul 11, 2025
ec7772f
ci: disable iOS Device Tests
Flash0ver Jul 11, 2025
15cc89c
release: 5.12.0-alpha.0
getsentry-bot Jul 11, 2025
305aee4
Merge branch 'release/5.12.0-alpha.0' into feat/logs-pre-release
Jul 11, 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
1 change: 1 addition & 0 deletions .github/workflows/device-tests-ios.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ on:

jobs:
ios-tests:
if: false
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

TODO: figure out why device tests on iOS are failing, it's unrelated to logs.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

We should be able to merge from main and revert this line now.

runs-on: macos-15
env:
DOTNET_CLI_TELEMETRY_OPTOUT: 1
Expand Down
10 changes: 9 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
# Changelog

## Unreleased
## 5.12.0-alpha.0

### 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))
- Add experimental integrations of [Sentry Structured Logging](https://docs.sentry.io/product/explore/logs/) ([#4193](https://github.com/getsentry/sentry-dotnet/pull/4193))
- `Sentry.AspNetCore`, enabled via `SentryAspNetCoreOptions.Experimental.EnableLogs`
- `Sentry.Extensions.Logging`, enabled via `SentryLoggingOptions.Experimental.EnableLogs`
- `Sentry.Maui`, enabled via `SentryMauiOptions.Experimental.EnableLogs`
### API changes

- App Hang Tracking for iOS is now disabled by default, until this functionality is more stable. If you want to use it in your applications then you'll need to enable this manually. ([#4320](https://github.com/getsentry/sentry-dotnet/pull/4320))

### 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))
- Added StartSpan and GetTransaction methods to the SentrySdk ([#4303](https://github.com/getsentry/sentry-dotnet/pull/4303))

### Fixes
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project>

<PropertyGroup>
<VersionPrefix>5.11.2</VersionPrefix>
<VersionPrefix>5.12.0-alpha.0</VersionPrefix>
<LangVersion>13</LangVersion>
<AccelerateBuildsInVisualStudio>true</AccelerateBuildsInVisualStudio>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
Expand Down
3 changes: 3 additions & 0 deletions samples/Sentry.Samples.AspNetCore.Basic/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
// Log debug information about the Sentry SDK
options.Debug = true;
#endif

// This option enables Logs sent to Sentry.
options.Experimental.EnableLogs = true;
});

var app = builder.Build();
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
10 changes: 10 additions & 0 deletions samples/Sentry.Samples.ME.Logging/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,17 @@
// Optionally configure options: The default values are:
options.MinimumBreadcrumbLevel = LogLevel.Information; // It requires at least this level to store breadcrumb
options.MinimumEventLevel = LogLevel.Error; // This level or above will result in event sent to Sentry
options.ExperimentalLogging.MinimumLogLevel = LogLevel.Trace; // This level or above will result in log sent to Sentry

// This option enables Logs sent to Sentry.
options.Experimental.EnableLogs = true;
options.Experimental.SetBeforeSendLog(static log =>
{
log.SetAttribute("attribute-key", "attribute-value");
return log;
});

// TODO: AddLogEntryFilter
// Don't keep as a breadcrumb or send events for messages of level less than Critical with exception of type DivideByZeroException
options.AddLogEntryFilter((_, level, _, exception) => level < LogLevel.Critical && exception is DivideByZeroException);

Expand Down
1 change: 1 addition & 0 deletions samples/Sentry.Samples.Maui/MauiProgram.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public static MauiApp CreateMauiApp()
options.AttachScreenshot = true;

options.Debug = true;
options.Experimental.EnableLogs = true;
options.SampleRate = 1.0F;

// The Sentry MVVM Community Toolkit integration automatically creates traces for async relay commands,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Sentry.Extensions.Logging;

namespace Sentry.AspNetCore;

/// <summary>
/// Structured Logger Provider for Sentry.
/// </summary>
[ProviderAlias("SentryLogs")]
[Experimental(Infrastructure.DiagnosticId.ExperimentalFeature)]
internal sealed class SentryAspNetCoreStructuredLoggerProvider : SentryStructuredLoggerProvider
{
public SentryAspNetCoreStructuredLoggerProvider(IOptions<SentryAspNetCoreOptions> options, IHub hub)
: base(options, hub)
{
}
}
6 changes: 6 additions & 0 deletions src/Sentry.AspNetCore/SentryWebHostBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,16 @@ public static IWebHostBuilder UseSentry(
_ = logging.Services
.AddSingleton<IConfigureOptions<SentryAspNetCoreOptions>, SentryAspNetCoreOptionsSetup>();
_ = logging.Services.AddSingleton<ILoggerProvider, SentryAspNetCoreLoggerProvider>();
_ = logging.Services.AddSingleton<ILoggerProvider, SentryAspNetCoreStructuredLoggerProvider>();

_ = logging.AddFilter<SentryAspNetCoreLoggerProvider>(
"Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware",
LogLevel.None);
_ = logging.AddFilter<SentryAspNetCoreStructuredLoggerProvider>(static (string? categoryName, LogLevel logLevel) =>
{
return categoryName is null
|| (categoryName != "Sentry.ISentryClient" && categoryName != "Sentry.AspNetCore.SentryMiddleware");
});

var sentryBuilder = logging.Services.AddSentry();
configureSentry?.Invoke(context, sentryBuilder);
Expand Down
11 changes: 11 additions & 0 deletions src/Sentry.Extensions.Logging/BindableSentryLoggingOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,22 @@ internal class BindableSentryLoggingOptions : BindableSentryOptions
public LogLevel? MinimumEventLevel { get; set; }
public bool? InitializeSdk { get; set; }

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

[Experimental(Infrastructure.DiagnosticId.ExperimentalFeature)]
internal sealed class BindableSentryLoggingExperimentalOptions
{
public LogLevel? MinimumLogLevel { get; set; }
}

public void ApplyTo(SentryLoggingOptions options)
{
base.ApplyTo(options);
options.MinimumBreadcrumbLevel = MinimumBreadcrumbLevel ?? options.MinimumBreadcrumbLevel;
options.MinimumEventLevel = MinimumEventLevel ?? options.MinimumEventLevel;
options.InitializeSdk = InitializeSdk ?? options.InitializeSdk;

options.ExperimentalLogging.MinimumLogLevel = ExperimentalLogging.MinimumLogLevel ?? options.ExperimentalLogging.MinimumLogLevel;
}
}
9 changes: 9 additions & 0 deletions src/Sentry.Extensions.Logging/LoggingBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,22 @@ internal static ILoggingBuilder AddSentry<TOptions>(

builder.Services.AddSingleton<IConfigureOptions<TOptions>, SentryLoggingOptionsSetup>();
builder.Services.AddSingleton<ILoggerProvider, SentryLoggerProvider>();
builder.Services.AddSingleton<ILoggerProvider, SentryStructuredLoggerProvider>();
builder.Services.AddSentry<TOptions>();

// All logs should flow to the SentryLogger, regardless of level.
// Filtering of events is handled in SentryLogger, using SentryOptions.MinimumEventLevel
// Filtering of breadcrumbs is handled in SentryLogger, using SentryOptions.MinimumBreadcrumbLevel
builder.AddFilter<SentryLoggerProvider>(_ => true);

// Logs from the SentryLogger should not flow to the SentryStructuredLogger as this may cause recursive invocations.
// Filtering of logs is handled in SentryStructuredLogger, using SentryOptions.MinimumLogLevel
builder.AddFilter<SentryStructuredLoggerProvider>(static (string? categoryName, LogLevel logLevel) =>
{
return categoryName is null
|| categoryName != "Sentry.ISentryClient";
});

return builder;
}
}
41 changes: 39 additions & 2 deletions src/Sentry.Extensions.Logging/SentryLoggingOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ public class SentryLoggingOptions : SentryOptions
/// <summary>
/// Gets or sets the minimum breadcrumb level.
/// </summary>
/// <remarks>Events with this level or higher will be stored as <see cref="Breadcrumb"/></remarks>
/// <remarks>
/// Events with this level or higher will be stored as <see cref="Breadcrumb"/>.
/// </remarks>
/// <value>
/// The minimum breadcrumb level.
/// </value>
Expand All @@ -21,7 +23,7 @@ public class SentryLoggingOptions : SentryOptions
/// Gets or sets the minimum event level.
/// </summary>
/// <remarks>
/// Events with this level or higher will be sent to Sentry
/// Events with this level or higher will be sent to Sentry.
/// </remarks>
/// <value>
/// The minimum event level.
Expand All @@ -48,4 +50,39 @@ public class SentryLoggingOptions : SentryOptions
/// List of callbacks to be invoked when initializing the SDK
/// </summary>
internal Action<Scope>[] ConfigureScopeCallbacks { get; set; } = Array.Empty<Action<Scope>>();

/// <summary>
/// Experimental Sentry Logging features.
/// </summary>
/// <remarks>
/// This and related experimental APIs may change in the future.
/// </remarks>
[Experimental(Infrastructure.DiagnosticId.ExperimentalFeature)]
public SentryLoggingExperimentalOptions ExperimentalLogging { get; set; } = new();

/// <summary>
/// Experimental Sentry Logging options.
/// </summary>
/// <remarks>
/// This and related experimental APIs may change in the future.
/// </remarks>
[Experimental(Infrastructure.DiagnosticId.ExperimentalFeature)]
public sealed class SentryLoggingExperimentalOptions
{
internal SentryLoggingExperimentalOptions()
{
}

/// <summary>
/// Gets or sets the minimum log level.
/// <para>This API is experimental and it may change in the future.</para>
/// </summary>
/// <remarks>
/// Logs with this level or higher will be stored as <see cref="SentryLog"/>.
/// </remarks>
/// <value>
/// The minimum log level.
/// </value>
public LogLevel MinimumLogLevel { get; set; } = LogLevel.Trace;
}
}
96 changes: 96 additions & 0 deletions src/Sentry.Extensions.Logging/SentryStructuredLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using Microsoft.Extensions.Logging;

namespace Sentry.Extensions.Logging;

[Experimental(Infrastructure.DiagnosticId.ExperimentalFeature)]
internal sealed class SentryStructuredLogger : ILogger
{
private readonly string _categoryName;
private readonly SentryLoggingOptions _options;
private readonly IHub _hub;

internal SentryStructuredLogger(string categoryName, SentryLoggingOptions options, IHub hub)
{
_categoryName = categoryName;
_options = options;
_hub = hub;
}

public IDisposable? BeginScope<TState>(TState state) where TState : notnull
{
return NullDisposable.Instance;
}

public bool IsEnabled(LogLevel logLevel)
{
return _hub.IsEnabled
&& _options.Experimental.EnableLogs
&& logLevel != LogLevel.None
&& logLevel >= _options.ExperimentalLogging.MinimumLogLevel;
}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}

// not quite ideal as this is a boxing allocation from Microsoft.Extensions.Logging.FormattedLogValues
/*
string? template = null;
object[]? parameters = null;
if (state is IReadOnlyList<KeyValuePair<string, object?>> formattedLogValues)
{
foreach (var formattedLogValue in formattedLogValues)
{
if (formattedLogValue.Key == "{OriginalFormat}" && formattedLogValue.Value is string formattedString)
{
template = formattedString;
break;
}
}
}
*/

string message = formatter.Invoke(state, exception);

switch (logLevel)
{
case LogLevel.Trace:
_hub.Logger.LogTrace(message);
break;
case LogLevel.Debug:
_hub.Logger.LogDebug(message);
break;
case LogLevel.Information:
_hub.Logger.LogInfo(message);
break;
case LogLevel.Warning:
_hub.Logger.LogWarning(message);
break;
case LogLevel.Error:
_hub.Logger.LogError(message);
break;
case LogLevel.Critical:
_hub.Logger.LogFatal(message);
break;
case LogLevel.None:
default:
break;
}
}
}

file sealed class NullDisposable : IDisposable
{
public static NullDisposable Instance { get; } = new NullDisposable();

private NullDisposable()
{
}

public void Dispose()
{
}
}
Loading
Loading