Skip to content

Commit 7f2bb84

Browse files
authored
Update Components to use LoggerMessage (#35585)
* Update Components to use LoggerMessage Contributes to #32087
1 parent 05303c7 commit 7f2bb84

14 files changed

+317
-881
lines changed

src/Components/Components/src/RenderTree/Renderer.Log.cs

Lines changed: 23 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,67 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4-
#nullable disable warnings
5-
6-
using System;
74
using Microsoft.AspNetCore.Components.Rendering;
85
using Microsoft.Extensions.Logging;
96

107
namespace Microsoft.AspNetCore.Components.RenderTree
118
{
129
public abstract partial class Renderer
1310
{
14-
internal static class Log
11+
internal static partial class Log
1512
{
16-
private static readonly LogDefineOptions SkipEnabledCheckLogOptions = new() { SkipEnabledCheck = true };
17-
18-
private static readonly Action<ILogger, int, Type, int, Type, Exception> _initializingChildComponent =
19-
LoggerMessage.Define<int, Type, int, Type>(LogLevel.Debug, new EventId(1, "InitializingChildComponent"), "Initializing component {ComponentId} ({ComponentType}) as child of {ParentComponentId} ({ParentComponentId})", SkipEnabledCheckLogOptions);
20-
21-
private static readonly Action<ILogger, int, Type, Exception> _initializingRootComponent =
22-
LoggerMessage.Define<int, Type>(LogLevel.Debug, new EventId(2, "InitializingRootComponent"), "Initializing root component {ComponentId} ({ComponentType})", SkipEnabledCheckLogOptions);
13+
[LoggerMessage(1, LogLevel.Debug, "Initializing component {ComponentId} ({ComponentType}) as child of {ParentComponentId} ({ParentComponentType})", EventName = "InitializingChildComponent", SkipEnabledCheck = true)]
14+
private static partial void InitializingChildComponent(ILogger logger, int componentId, Type componentType, int parentComponentId, Type parentComponentType);
2315

24-
private static readonly Action<ILogger, int, Type, Exception> _renderingComponent =
25-
LoggerMessage.Define<int, Type>(LogLevel.Debug, new EventId(3, "RenderingComponent"), "Rendering component {ComponentId} of type {ComponentType}", SkipEnabledCheckLogOptions);
26-
27-
private static readonly Action<ILogger, int, Type, Exception> _disposingComponent =
28-
LoggerMessage.Define<int, Type>(LogLevel.Debug, new EventId(4, "DisposingComponent"), "Disposing component {ComponentId} of type {ComponentType}", SkipEnabledCheckLogOptions);
29-
30-
private static readonly Action<ILogger, ulong, string, Exception> _handlingEvent =
31-
LoggerMessage.Define<ulong, string>(LogLevel.Debug, new EventId(5, "HandlingEvent"), "Handling event {EventId} of type '{EventType}'");
16+
[LoggerMessage(2, LogLevel.Debug, "Initializing root component {ComponentId} ({ComponentType})", EventName = "InitializingRootComponent", SkipEnabledCheck = true)]
17+
private static partial void InitializingRootComponent(ILogger logger, int componentId, Type componentType);
3218

3319
public static void InitializingComponent(ILogger logger, ComponentState componentState, ComponentState parentComponentState)
3420
{
3521
if (logger.IsEnabled(LogLevel.Debug)) // This is almost always false, so skip the evaluations
3622
{
3723
if (parentComponentState == null)
3824
{
39-
_initializingRootComponent(logger, componentState.ComponentId, componentState.Component.GetType(), null);
25+
InitializingRootComponent(logger, componentState.ComponentId, componentState.Component.GetType());
4026
}
4127
else
4228
{
43-
_initializingChildComponent(logger, componentState.ComponentId, componentState.Component.GetType(), parentComponentState.ComponentId, parentComponentState.Component.GetType(), null);
29+
InitializingChildComponent(logger, componentState.ComponentId, componentState.Component.GetType(), parentComponentState.ComponentId, parentComponentState.Component.GetType());
4430
}
4531
}
4632
}
4733

34+
[LoggerMessage(3, LogLevel.Debug, "Rendering component {ComponentId} of type {ComponentType}", EventName = "RenderingComponent", SkipEnabledCheck = true)]
35+
private static partial void RenderingComponent(ILogger logger, int componentId, Type componentType);
36+
4837
public static void RenderingComponent(ILogger logger, ComponentState componentState)
4938
{
5039
if (logger.IsEnabled(LogLevel.Debug)) // This is almost always false, so skip the evaluations
5140
{
52-
_renderingComponent(logger, componentState.ComponentId, componentState.Component.GetType(), null);
41+
RenderingComponent(logger, componentState.ComponentId, componentState.Component.GetType());
5342
}
5443
}
5544

45+
[LoggerMessage(4, LogLevel.Debug, "Disposing component {ComponentId} of type {ComponentType}", EventName = "DisposingComponent", SkipEnabledCheck = true)]
46+
private static partial void DisposingComponent(ILogger<Renderer> logger, int componentId, Type componentType);
47+
5648
public static void DisposingComponent(ILogger<Renderer> logger, ComponentState componentState)
5749
{
5850
if (logger.IsEnabled(LogLevel.Debug)) // This is almost always false, so skip the evaluations
5951
{
60-
_disposingComponent(logger, componentState.ComponentId, componentState.Component.GetType(), null);
52+
DisposingComponent(logger, componentState.ComponentId, componentState.Component.GetType());
6153
}
6254
}
6355

64-
public static void HandlingEvent(ILogger<Renderer> logger, ulong eventHandlerId, EventArgs eventArgs)
56+
[LoggerMessage(5, LogLevel.Debug, "Handling event {EventId} of type '{EventType}'", EventName = "HandlingEvent", SkipEnabledCheck = true)]
57+
public static partial void HandlingEvent(ILogger<Renderer> logger, ulong eventId, string eventType);
58+
59+
public static void HandlingEvent(ILogger<Renderer> logger, ulong eventHandlerId, EventArgs? eventArgs)
6560
{
66-
_handlingEvent(logger, eventHandlerId, eventArgs?.GetType().Name ?? "null", null);
61+
if (logger.IsEnabled(LogLevel.Debug)) // This is almost always false, so skip the evaluations
62+
{
63+
HandlingEvent(logger, eventHandlerId, eventArgs?.GetType().Name ?? "null");
64+
}
6765
}
6866
}
6967
}

src/Components/Components/src/Routing/Router.cs

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,9 @@
33

44
#nullable disable warnings
55

6-
using System;
7-
using System.Collections.Generic;
86
using System.Reflection;
97
using System.Reflection.Metadata;
108
using System.Runtime.ExceptionServices;
11-
using System.Threading;
12-
using System.Threading.Tasks;
139
using Microsoft.AspNetCore.Components.HotReload;
1410
using Microsoft.Extensions.Logging;
1511

@@ -18,7 +14,7 @@ namespace Microsoft.AspNetCore.Components.Routing
1814
/// <summary>
1915
/// A component that supplies route data corresponding to the current navigation state.
2016
/// </summary>
21-
public class Router : IComponent, IHandleAfterRender, IDisposable
17+
public partial class Router : IComponent, IHandleAfterRender, IDisposable
2218
{
2319
static readonly char[] _queryOrHashStartChar = new[] { '?', '#' };
2420
// Dictionary is intentionally used instead of ReadOnlyDictionary to reduce Blazor size
@@ -292,31 +288,16 @@ Task IHandleAfterRender.OnAfterRenderAsync()
292288
return Task.CompletedTask;
293289
}
294290

295-
private static class Log
291+
private static partial class Log
296292
{
297-
private static readonly Action<ILogger, string, string, Exception> _displayingNotFound =
298-
LoggerMessage.Define<string, string>(LogLevel.Debug, new EventId(1, "DisplayingNotFound"), $"Displaying {nameof(NotFound)} because path '{{Path}}' with base URI '{{BaseUri}}' does not match any component route");
293+
[LoggerMessage(1, LogLevel.Debug, $"Displaying {nameof(NotFound)} because path '{{Path}}' with base URI '{{BaseUri}}' does not match any component route", EventName = "DisplayingNotFound")]
294+
internal static partial void DisplayingNotFound(ILogger logger, string path, string baseUri);
299295

300-
private static readonly Action<ILogger, Type, string, string, Exception> _navigatingToComponent =
301-
LoggerMessage.Define<Type, string, string>(LogLevel.Debug, new EventId(2, "NavigatingToComponent"), "Navigating to component {ComponentType} in response to path '{Path}' with base URI '{BaseUri}'");
296+
[LoggerMessage(2, LogLevel.Debug, "Navigating to component {ComponentType} in response to path '{Path}' with base URI '{BaseUri}'", EventName = "NavigatingToComponent")]
297+
internal static partial void NavigatingToComponent(ILogger logger, Type componentType, string path, string baseUri);
302298

303-
private static readonly Action<ILogger, string, string, string, Exception> _navigatingToExternalUri =
304-
LoggerMessage.Define<string, string, string>(LogLevel.Debug, new EventId(3, "NavigatingToExternalUri"), "Navigating to non-component URI '{ExternalUri}' in response to path '{Path}' with base URI '{BaseUri}'");
305-
306-
internal static void DisplayingNotFound(ILogger logger, string path, string baseUri)
307-
{
308-
_displayingNotFound(logger, path, baseUri, null);
309-
}
310-
311-
internal static void NavigatingToComponent(ILogger logger, Type componentType, string path, string baseUri)
312-
{
313-
_navigatingToComponent(logger, componentType, path, baseUri, null);
314-
}
315-
316-
internal static void NavigatingToExternalUri(ILogger logger, string externalUri, string path, string baseUri)
317-
{
318-
_navigatingToExternalUri(logger, externalUri, path, baseUri, null);
319-
}
299+
[LoggerMessage(3, LogLevel.Debug, "Navigating to non-component URI '{ExternalUri}' in response to path '{Path}' with base URI '{BaseUri}'", EventName = "NavigatingToExternalUri")]
300+
internal static partial void NavigatingToExternalUri(ILogger logger, string externalUri, string path, string baseUri);
320301
}
321302
}
322303
}

src/Components/Server/src/CircuitDisconnectMiddleware.cs

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4-
using System;
5-
using System.Threading.Tasks;
64
using Microsoft.AspNetCore.Components.Server.Circuits;
75
using Microsoft.AspNetCore.Http;
86
using Microsoft.Extensions.Logging;
97

108
namespace Microsoft.AspNetCore.Components.Server
119
{
1210
// We use a middleware so that we can use DI.
13-
internal class CircuitDisconnectMiddleware
11+
internal sealed partial class CircuitDisconnectMiddleware
1412
{
1513
private const string CircuitIdKey = "circuitId";
1614

@@ -88,22 +86,16 @@ private async Task TerminateCircuitGracefully(CircuitId circuitId)
8886
Log.CircuitTerminatedGracefully(Logger, circuitId);
8987
}
9088

91-
private class Log
89+
private static partial class Log
9290
{
93-
private static readonly Action<ILogger, CircuitId, Exception> _circuitTerminatingGracefully =
94-
LoggerMessage.Define<CircuitId>(LogLevel.Debug, new EventId(1, "CircuitTerminatingGracefully"), "Circuit with id '{CircuitId}' terminating gracefully.");
91+
[LoggerMessage(1, LogLevel.Debug, "Circuit with id '{CircuitId}' terminating gracefully.", EventName = "CircuitTerminatingGracefully")]
92+
public static partial void CircuitTerminatingGracefully(ILogger logger, CircuitId circuitId);
9593

96-
private static readonly Action<ILogger, CircuitId, Exception> _circuitTerminatedGracefully =
97-
LoggerMessage.Define<CircuitId>(LogLevel.Debug, new EventId(2, "CircuitTerminatedGracefully"), "Circuit with id '{CircuitId}' terminated gracefully.");
94+
[LoggerMessage(2, LogLevel.Debug, "Circuit with id '{CircuitId}' terminated gracefully.", EventName = "CircuitTerminatedGracefully")]
95+
public static partial void CircuitTerminatedGracefully(ILogger logger, CircuitId circuitId);
9896

99-
private static readonly Action<ILogger, string, Exception> _invalidCircuitId =
100-
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(3, "InvalidCircuitId"), "CircuitDisconnectMiddleware received an invalid circuit id '{CircuitIdSecret}'.");
101-
102-
public static void CircuitTerminatingGracefully(ILogger logger, CircuitId circuitId) => _circuitTerminatingGracefully(logger, circuitId, null);
103-
104-
public static void CircuitTerminatedGracefully(ILogger logger, CircuitId circuitId) => _circuitTerminatedGracefully(logger, circuitId, null);
105-
106-
public static void InvalidCircuitId(ILogger logger, string circuitSecret) => _invalidCircuitId(logger, circuitSecret, null);
97+
[LoggerMessage(3, LogLevel.Debug, "CircuitDisconnectMiddleware received an invalid circuit id '{CircuitIdSecret}'.", EventName = "InvalidCircuitId")]
98+
public static partial void InvalidCircuitId(ILogger logger, string circuitIdSecret);
10799
}
108100
}
109101
}

src/Components/Server/src/Circuits/CircuitFactory.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
namespace Microsoft.AspNetCore.Components.Server.Circuits
1818
{
19-
internal class CircuitFactory : ICircuitFactory
19+
internal sealed partial class CircuitFactory : ICircuitFactory
2020
{
2121
private readonly IServiceScopeFactory _scopeFactory;
2222
private readonly ILoggerFactory _loggerFactory;
@@ -99,13 +99,13 @@ public async ValueTask<CircuitHost> CreateCircuitHostAsync(
9999
return circuitHost;
100100
}
101101

102-
private static class Log
102+
private static partial class Log
103103
{
104-
private static readonly Action<ILogger, string, string, Exception> _createdCircuit =
105-
LoggerMessage.Define<string, string>(LogLevel.Debug, new EventId(1, "CreatedCircuit"), "Created circuit {CircuitId} for connection {ConnectionId}");
104+
[LoggerMessage(1, LogLevel.Debug, "Created circuit {CircuitId} for connection {ConnectionId}", EventName = "CreatedCircuit")]
105+
private static partial void CreatedCircuit(ILogger logger, string circuitId, string connectionId);
106106

107107
internal static void CreatedCircuit(ILogger logger, CircuitHost circuitHost) =>
108-
_createdCircuit(logger, circuitHost.CircuitId.Id, circuitHost.Client.ConnectionId, null);
108+
CreatedCircuit(logger, circuitHost.CircuitId.Id, circuitHost.Client.ConnectionId);
109109
}
110110
}
111111
}

0 commit comments

Comments
 (0)