Skip to content

Commit

Permalink
Update Components to use LoggerMessage (#35585)
Browse files Browse the repository at this point in the history
* Update Components to use LoggerMessage

Contributes to #32087
  • Loading branch information
pranavkm authored Aug 31, 2021
1 parent 05303c7 commit 7f2bb84
Show file tree
Hide file tree
Showing 14 changed files with 317 additions and 881 deletions.
48 changes: 23 additions & 25 deletions src/Components/Components/src/RenderTree/Renderer.Log.cs
Original file line number Diff line number Diff line change
@@ -1,69 +1,67 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#nullable disable warnings

using System;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Components.RenderTree
{
public abstract partial class Renderer
{
internal static class Log
internal static partial class Log
{
private static readonly LogDefineOptions SkipEnabledCheckLogOptions = new() { SkipEnabledCheck = true };

private static readonly Action<ILogger, int, Type, int, Type, Exception> _initializingChildComponent =
LoggerMessage.Define<int, Type, int, Type>(LogLevel.Debug, new EventId(1, "InitializingChildComponent"), "Initializing component {ComponentId} ({ComponentType}) as child of {ParentComponentId} ({ParentComponentId})", SkipEnabledCheckLogOptions);

private static readonly Action<ILogger, int, Type, Exception> _initializingRootComponent =
LoggerMessage.Define<int, Type>(LogLevel.Debug, new EventId(2, "InitializingRootComponent"), "Initializing root component {ComponentId} ({ComponentType})", SkipEnabledCheckLogOptions);
[LoggerMessage(1, LogLevel.Debug, "Initializing component {ComponentId} ({ComponentType}) as child of {ParentComponentId} ({ParentComponentType})", EventName = "InitializingChildComponent", SkipEnabledCheck = true)]
private static partial void InitializingChildComponent(ILogger logger, int componentId, Type componentType, int parentComponentId, Type parentComponentType);

private static readonly Action<ILogger, int, Type, Exception> _renderingComponent =
LoggerMessage.Define<int, Type>(LogLevel.Debug, new EventId(3, "RenderingComponent"), "Rendering component {ComponentId} of type {ComponentType}", SkipEnabledCheckLogOptions);

private static readonly Action<ILogger, int, Type, Exception> _disposingComponent =
LoggerMessage.Define<int, Type>(LogLevel.Debug, new EventId(4, "DisposingComponent"), "Disposing component {ComponentId} of type {ComponentType}", SkipEnabledCheckLogOptions);

private static readonly Action<ILogger, ulong, string, Exception> _handlingEvent =
LoggerMessage.Define<ulong, string>(LogLevel.Debug, new EventId(5, "HandlingEvent"), "Handling event {EventId} of type '{EventType}'");
[LoggerMessage(2, LogLevel.Debug, "Initializing root component {ComponentId} ({ComponentType})", EventName = "InitializingRootComponent", SkipEnabledCheck = true)]
private static partial void InitializingRootComponent(ILogger logger, int componentId, Type componentType);

public static void InitializingComponent(ILogger logger, ComponentState componentState, ComponentState parentComponentState)
{
if (logger.IsEnabled(LogLevel.Debug)) // This is almost always false, so skip the evaluations
{
if (parentComponentState == null)
{
_initializingRootComponent(logger, componentState.ComponentId, componentState.Component.GetType(), null);
InitializingRootComponent(logger, componentState.ComponentId, componentState.Component.GetType());
}
else
{
_initializingChildComponent(logger, componentState.ComponentId, componentState.Component.GetType(), parentComponentState.ComponentId, parentComponentState.Component.GetType(), null);
InitializingChildComponent(logger, componentState.ComponentId, componentState.Component.GetType(), parentComponentState.ComponentId, parentComponentState.Component.GetType());
}
}
}

[LoggerMessage(3, LogLevel.Debug, "Rendering component {ComponentId} of type {ComponentType}", EventName = "RenderingComponent", SkipEnabledCheck = true)]
private static partial void RenderingComponent(ILogger logger, int componentId, Type componentType);

public static void RenderingComponent(ILogger logger, ComponentState componentState)
{
if (logger.IsEnabled(LogLevel.Debug)) // This is almost always false, so skip the evaluations
{
_renderingComponent(logger, componentState.ComponentId, componentState.Component.GetType(), null);
RenderingComponent(logger, componentState.ComponentId, componentState.Component.GetType());
}
}

[LoggerMessage(4, LogLevel.Debug, "Disposing component {ComponentId} of type {ComponentType}", EventName = "DisposingComponent", SkipEnabledCheck = true)]
private static partial void DisposingComponent(ILogger<Renderer> logger, int componentId, Type componentType);

public static void DisposingComponent(ILogger<Renderer> logger, ComponentState componentState)
{
if (logger.IsEnabled(LogLevel.Debug)) // This is almost always false, so skip the evaluations
{
_disposingComponent(logger, componentState.ComponentId, componentState.Component.GetType(), null);
DisposingComponent(logger, componentState.ComponentId, componentState.Component.GetType());
}
}

public static void HandlingEvent(ILogger<Renderer> logger, ulong eventHandlerId, EventArgs eventArgs)
[LoggerMessage(5, LogLevel.Debug, "Handling event {EventId} of type '{EventType}'", EventName = "HandlingEvent", SkipEnabledCheck = true)]
public static partial void HandlingEvent(ILogger<Renderer> logger, ulong eventId, string eventType);

public static void HandlingEvent(ILogger<Renderer> logger, ulong eventHandlerId, EventArgs? eventArgs)
{
_handlingEvent(logger, eventHandlerId, eventArgs?.GetType().Name ?? "null", null);
if (logger.IsEnabled(LogLevel.Debug)) // This is almost always false, so skip the evaluations
{
HandlingEvent(logger, eventHandlerId, eventArgs?.GetType().Name ?? "null");
}
}
}
}
Expand Down
35 changes: 8 additions & 27 deletions src/Components/Components/src/Routing/Router.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,9 @@

#nullable disable warnings

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.HotReload;
using Microsoft.Extensions.Logging;

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

private static class Log
private static partial class Log
{
private static readonly Action<ILogger, string, string, Exception> _displayingNotFound =
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");
[LoggerMessage(1, LogLevel.Debug, $"Displaying {nameof(NotFound)} because path '{{Path}}' with base URI '{{BaseUri}}' does not match any component route", EventName = "DisplayingNotFound")]
internal static partial void DisplayingNotFound(ILogger logger, string path, string baseUri);

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

private static readonly Action<ILogger, string, string, string, Exception> _navigatingToExternalUri =
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}'");

internal static void DisplayingNotFound(ILogger logger, string path, string baseUri)
{
_displayingNotFound(logger, path, baseUri, null);
}

internal static void NavigatingToComponent(ILogger logger, Type componentType, string path, string baseUri)
{
_navigatingToComponent(logger, componentType, path, baseUri, null);
}

internal static void NavigatingToExternalUri(ILogger logger, string externalUri, string path, string baseUri)
{
_navigatingToExternalUri(logger, externalUri, path, baseUri, null);
}
[LoggerMessage(3, LogLevel.Debug, "Navigating to non-component URI '{ExternalUri}' in response to path '{Path}' with base URI '{BaseUri}'", EventName = "NavigatingToExternalUri")]
internal static partial void NavigatingToExternalUri(ILogger logger, string externalUri, string path, string baseUri);
}
}
}
24 changes: 8 additions & 16 deletions src/Components/Server/src/CircuitDisconnectMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Server.Circuits;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Components.Server
{
// We use a middleware so that we can use DI.
internal class CircuitDisconnectMiddleware
internal sealed partial class CircuitDisconnectMiddleware
{
private const string CircuitIdKey = "circuitId";

Expand Down Expand Up @@ -88,22 +86,16 @@ private async Task TerminateCircuitGracefully(CircuitId circuitId)
Log.CircuitTerminatedGracefully(Logger, circuitId);
}

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

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

private static readonly Action<ILogger, string, Exception> _invalidCircuitId =
LoggerMessage.Define<string>(LogLevel.Debug, new EventId(3, "InvalidCircuitId"), "CircuitDisconnectMiddleware received an invalid circuit id '{CircuitIdSecret}'.");

public static void CircuitTerminatingGracefully(ILogger logger, CircuitId circuitId) => _circuitTerminatingGracefully(logger, circuitId, null);

public static void CircuitTerminatedGracefully(ILogger logger, CircuitId circuitId) => _circuitTerminatedGracefully(logger, circuitId, null);

public static void InvalidCircuitId(ILogger logger, string circuitSecret) => _invalidCircuitId(logger, circuitSecret, null);
[LoggerMessage(3, LogLevel.Debug, "CircuitDisconnectMiddleware received an invalid circuit id '{CircuitIdSecret}'.", EventName = "InvalidCircuitId")]
public static partial void InvalidCircuitId(ILogger logger, string circuitIdSecret);
}
}
}
10 changes: 5 additions & 5 deletions src/Components/Server/src/Circuits/CircuitFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

namespace Microsoft.AspNetCore.Components.Server.Circuits
{
internal class CircuitFactory : ICircuitFactory
internal sealed partial class CircuitFactory : ICircuitFactory
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILoggerFactory _loggerFactory;
Expand Down Expand Up @@ -99,13 +99,13 @@ public async ValueTask<CircuitHost> CreateCircuitHostAsync(
return circuitHost;
}

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

internal static void CreatedCircuit(ILogger logger, CircuitHost circuitHost) =>
_createdCircuit(logger, circuitHost.CircuitId.Id, circuitHost.Client.ConnectionId, null);
CreatedCircuit(logger, circuitHost.CircuitId.Id, circuitHost.Client.ConnectionId);
}
}
}
Loading

0 comments on commit 7f2bb84

Please sign in to comment.