-
Notifications
You must be signed in to change notification settings - Fork 670
Fix Blazor error logging to telemetry #9304
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
31 changes: 0 additions & 31 deletions
31
src/Aspire.Dashboard/Components/Controls/TelemetryErrorBoundary.cs
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Aspire.Dashboard.Telemetry; | ||
|
||
/// <summary> | ||
/// Log an error to dashboard telemetry when there is an unhandled Blazor error. | ||
/// </summary> | ||
public sealed class TelemetryLoggerProvider : ILoggerProvider | ||
{ | ||
// Log when an unhandled error is caught by Blazor. | ||
// https://github.com/dotnet/aspnetcore/blob/0230498dfccaef6f782a5e37c60ea505081b72bf/src/Components/Server/src/Circuits/CircuitHost.cs#L695 | ||
public const string CircuitHostLogCategory = "Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost"; | ||
public static readonly EventId CircuitUnhandledExceptionEventId = new EventId(111, "CircuitUnhandledException"); | ||
|
||
private readonly IServiceProvider _serviceProvider; | ||
|
||
public TelemetryLoggerProvider(IServiceProvider serviceProvider) | ||
{ | ||
_serviceProvider = serviceProvider; | ||
} | ||
|
||
public ILogger CreateLogger(string categoryName) => new TelemetryLogger(_serviceProvider, categoryName); | ||
|
||
public void Dispose() | ||
{ | ||
} | ||
|
||
private sealed class TelemetryLogger : ILogger | ||
{ | ||
private readonly IServiceProvider _serviceProvider; | ||
private readonly bool _isCircuitHostLogger; | ||
|
||
public TelemetryLogger(IServiceProvider serviceProvider, string categoryName) | ||
{ | ||
_serviceProvider = serviceProvider; | ||
_isCircuitHostLogger = categoryName == CircuitHostLogCategory; | ||
} | ||
|
||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null; | ||
|
||
public bool IsEnabled(LogLevel logLevel) => true; | ||
|
||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) | ||
{ | ||
if (_isCircuitHostLogger && eventId == CircuitUnhandledExceptionEventId && exception != null) | ||
{ | ||
try | ||
{ | ||
// Get the telemetry service lazily to avoid a circular reference between resolving telemetry service and logging. | ||
var telemetryService = _serviceProvider.GetRequiredService<DashboardTelemetryService>(); | ||
|
||
telemetryService.PostFault( | ||
TelemetryEventKeys.Error, | ||
$"{exception.GetType().FullName}: {exception.Message}", | ||
FaultSeverity.Critical, | ||
new Dictionary<string, AspireTelemetryProperty> | ||
{ | ||
[TelemetryPropertyKeys.ExceptionType] = new AspireTelemetryProperty(exception.GetType().FullName!), | ||
[TelemetryPropertyKeys.ExceptionMessage] = new AspireTelemetryProperty(exception.Message), | ||
[TelemetryPropertyKeys.ExceptionStackTrace] = new AspireTelemetryProperty(exception.StackTrace ?? string.Empty) | ||
} | ||
); | ||
} | ||
catch | ||
{ | ||
// We should never throw an error out of logging. | ||
// Logging the error to telemetry shouldn't throw. But, for extra safety, send error to telemetry is inside a try/catch. | ||
} | ||
} | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
tests/Aspire.Dashboard.Tests/Telemetry/TelemetryLoggerProviderTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Aspire.Dashboard.Telemetry; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Logging; | ||
using Xunit; | ||
|
||
namespace Aspire.Dashboard.Tests.Telemetry; | ||
|
||
public class TelemetryLoggerProviderTests | ||
{ | ||
[Fact] | ||
public async Task Log_DifferentCategoryAndEventIds_WriteTelemetryForBlazorUnhandedErrorAsync() | ||
{ | ||
// Arrange | ||
var telemetrySender = new TestDashboardTelemetrySender { IsTelemetryEnabled = true }; | ||
await telemetrySender.TryStartTelemetrySessionAsync(); | ||
|
||
var serviceProvider = new ServiceCollection() | ||
.AddSingleton<DashboardTelemetryService>() | ||
.AddSingleton<IDashboardTelemetrySender>(telemetrySender) | ||
.AddLogging() | ||
.AddSingleton<ILoggerProvider, TelemetryLoggerProvider>() | ||
.BuildServiceProvider(); | ||
|
||
var loggerProvider = serviceProvider.GetRequiredService<ILoggerFactory>(); | ||
|
||
// Act & assert 1 | ||
var testLogger = loggerProvider.CreateLogger("testLogger"); | ||
testLogger.Log(LogLevel.Error, TelemetryLoggerProvider.CircuitUnhandledExceptionEventId, "Test message"); | ||
Assert.False(telemetrySender.ContextChannel.Reader.TryPeek(out _)); | ||
|
||
// Act & assert 2 | ||
var circuitHostLogger = loggerProvider.CreateLogger(TelemetryLoggerProvider.CircuitHostLogCategory); | ||
circuitHostLogger.LogInformation("Test log message"); | ||
Assert.False(telemetrySender.ContextChannel.Reader.TryPeek(out _)); | ||
|
||
// Act & assert 3 | ||
circuitHostLogger.Log(LogLevel.Error, TelemetryLoggerProvider.CircuitUnhandledExceptionEventId, "Test message"); | ||
Assert.False(telemetrySender.ContextChannel.Reader.TryPeek(out _)); | ||
|
||
// Act & assert 4 | ||
circuitHostLogger.Log(LogLevel.Error, TelemetryLoggerProvider.CircuitUnhandledExceptionEventId, new InvalidOperationException("Exception message"), "Test message"); | ||
Assert.True(telemetrySender.ContextChannel.Reader.TryPeek(out var context)); | ||
Assert.Equal("/telemetry/fault - $aspire/dashboard/error", context.Name); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm assuming this usage pattern adds a further
ILoggerProvider
rather than replacing the one that would already have been in place, so you still get normal logging output.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes. It's what happens when you call
LoggerFactory.AddProvider
: https://github.com/dotnet/runtime/blob/f76d75739482939fcf2661010bf490a3d81163ed/src/libraries/Microsoft.Extensions.Logging/src/LoggingBuilderExtensions.cs#L37Other methods to add customer loggers use
TryAddEnumerable
. Example. I think that's to avoid double registration of a provider which isn't a problem in our case because we control all registrations in the dashboard app.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@SteveSandersonMS I added a test.