Skip to content
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

Use LoggerMessageAttribute in more places #40297

Merged
merged 4 commits into from
Feb 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
112 changes: 22 additions & 90 deletions src/Antiforgery/src/Internal/AntiforgeryLoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,103 +5,35 @@

namespace Microsoft.AspNetCore.Antiforgery;

internal static class AntiforgeryLoggerExtensions
internal static partial class AntiforgeryLoggerExtensions
{
private static readonly Action<ILogger, Exception?> _failedToDeserialzeTokens;
private static readonly Action<ILogger, string, Exception?> _validationFailed;
private static readonly Action<ILogger, Exception?> _validated;
private static readonly Action<ILogger, string?, Exception?> _missingCookieToken;
private static readonly Action<ILogger, string, string?, Exception?> _missingRequestToken;
private static readonly Action<ILogger, Exception?> _newCookieToken;
private static readonly Action<ILogger, Exception?> _reusedCookieToken;
private static readonly Action<ILogger, Exception?> _tokenDeserializeException;
private static readonly Action<ILogger, Exception?> _responseCacheHeadersOverridenToNoCache;
[LoggerMessage(1, LogLevel.Warning, "Antiforgery validation failed with message '{Message}'.", EventName = "ValidationFailed")]
public static partial void ValidationFailed(this ILogger logger, string message);

static AntiforgeryLoggerExtensions()
{
_validationFailed = LoggerMessage.Define<string>(
LogLevel.Warning,
new EventId(1, "ValidationFailed"),
"Antiforgery validation failed with message '{Message}'.");
_validated = LoggerMessage.Define(
LogLevel.Debug,
new EventId(2, "Validated"),
"Antiforgery successfully validated a request.");
_missingCookieToken = LoggerMessage.Define<string?>(
LogLevel.Warning,
new EventId(3, "MissingCookieToken"),
"The required antiforgery cookie '{CookieName}' is not present.");
_missingRequestToken = LoggerMessage.Define<string, string?>(
LogLevel.Warning,
new EventId(4, "MissingRequestToken"),
"The required antiforgery request token was not provided in either form field '{FormFieldName}' "
+ "or header '{HeaderName}'.");
_newCookieToken = LoggerMessage.Define(
LogLevel.Debug,
new EventId(5, "NewCookieToken"),
"A new antiforgery cookie token was created.");
_reusedCookieToken = LoggerMessage.Define(
LogLevel.Debug,
new EventId(6, "ReusedCookieToken"),
"An antiforgery cookie token was reused.");
_tokenDeserializeException = LoggerMessage.Define(
LogLevel.Error,
new EventId(7, "TokenDeserializeException"),
"An exception was thrown while deserializing the token.");
_responseCacheHeadersOverridenToNoCache = LoggerMessage.Define(
LogLevel.Warning,
new EventId(8, "ResponseCacheHeadersOverridenToNoCache"),
"The 'Cache-Control' and 'Pragma' headers have been overridden and set to 'no-cache, no-store' and " +
"'no-cache' respectively to prevent caching of this response. Any response that uses antiforgery " +
"should not be cached.");
_failedToDeserialzeTokens = LoggerMessage.Define(
LogLevel.Debug,
new EventId(9, "FailedToDeserialzeTokens"),
"Failed to deserialize antiforgery tokens.");
}

public static void ValidationFailed(this ILogger logger, string message)
{
_validationFailed(logger, message, null);
}
[LoggerMessage(2, LogLevel.Debug, "Antiforgery successfully validated a request.", EventName = "Validated")]
public static partial void ValidatedAntiforgeryToken(this ILogger logger);

public static void ValidatedAntiforgeryToken(this ILogger logger)
{
_validated(logger, null);
}
[LoggerMessage(3, LogLevel.Warning, "The required antiforgery cookie '{CookieName}' is not present.", EventName = "MissingCookieToken")]
public static partial void MissingCookieToken(this ILogger logger, string? cookieName);

public static void MissingCookieToken(this ILogger logger, string? cookieName)
{
_missingCookieToken(logger, cookieName, null);
}
[LoggerMessage(4, LogLevel.Warning, "The required antiforgery request token was not provided in either form field '{FormFieldName}' "
+ "or header '{HeaderName}'.", EventName = "MissingRequestToken")]
public static partial void MissingRequestToken(this ILogger logger, string formFieldName, string? headerName);

public static void MissingRequestToken(this ILogger logger, string formFieldName, string? headerName)
{
_missingRequestToken(logger, formFieldName, headerName, null);
}
[LoggerMessage(5, LogLevel.Debug, "A new antiforgery cookie token was created.", EventName = "NewCookieToken")]
public static partial void NewCookieToken(this ILogger logger);

public static void NewCookieToken(this ILogger logger)
{
_newCookieToken(logger, null);
}
[LoggerMessage(6, LogLevel.Debug, "An antiforgery cookie token was reused.", EventName = "ReusedCookieToken")]
public static partial void ReusedCookieToken(this ILogger logger);

public static void ReusedCookieToken(this ILogger logger)
{
_reusedCookieToken(logger, null);
}
[LoggerMessage(7, LogLevel.Error, "An exception was thrown while deserializing the token.", EventName = "TokenDeserializeException")]
public static partial void TokenDeserializeException(this ILogger logger, Exception exception);

public static void TokenDeserializeException(this ILogger logger, Exception exception)
{
_tokenDeserializeException(logger, exception);
}

public static void ResponseCacheHeadersOverridenToNoCache(this ILogger logger)
{
_responseCacheHeadersOverridenToNoCache(logger, null);
}
[LoggerMessage(8, LogLevel.Warning, "The 'Cache-Control' and 'Pragma' headers have been overridden and set to 'no-cache, no-store' and " +
"'no-cache' respectively to prevent caching of this response. Any response that uses antiforgery " +
"should not be cached.", EventName = "ResponseCacheHeadersOverridenToNoCache")]
public static partial void ResponseCacheHeadersOverridenToNoCache(this ILogger logger);

public static void FailedToDeserialzeTokens(this ILogger logger, Exception exception)
{
_failedToDeserialzeTokens(logger, exception);
}
[LoggerMessage(9, LogLevel.Debug, "Failed to deserialize antiforgery tokens.", EventName = "FailedToDeserialzeTokens")]
public static partial void FailedToDeserialzeTokens(this ILogger logger, Exception exception);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Rendering;
/// Provides mechanisms for rendering <see cref="IComponent"/> instances in a
/// web browser, dispatching events to them, and refreshing the UI as required.
/// </summary>
internal class WebAssemblyRenderer : WebRenderer
internal partial class WebAssemblyRenderer : WebRenderer
{
private readonly ILogger _logger;

Expand Down Expand Up @@ -113,33 +113,18 @@ protected override void HandleException(Exception exception)
{
foreach (var innerException in aggregateException.Flatten().InnerExceptions)
{
Log.UnhandledExceptionRenderingComponent(_logger, innerException);
Log.UnhandledExceptionRenderingComponent(_logger, innerException.Message, innerException);
}
}
else
{
Log.UnhandledExceptionRenderingComponent(_logger, exception);
Log.UnhandledExceptionRenderingComponent(_logger, exception.Message, exception);
}
}

private static class Log
private static partial class Log
{
private static readonly Action<ILogger, string, Exception> _unhandledExceptionRenderingComponent = LoggerMessage.Define<string>(
LogLevel.Critical,
EventIds.UnhandledExceptionRenderingComponent,
"Unhandled exception rendering component: {Message}");

private static class EventIds
{
public static readonly EventId UnhandledExceptionRenderingComponent = new EventId(100, "ExceptionRenderingComponent");
}

public static void UnhandledExceptionRenderingComponent(ILogger logger, Exception exception)
{
_unhandledExceptionRenderingComponent(
logger,
exception.Message,
exception);
}
[LoggerMessage(100, LogLevel.Critical, "Unhandled exception rendering component: {Message}", EventName = "ExceptionRenderingComponent")]
public static partial void UnhandledExceptionRenderingComponent(ILogger logger, string message, Exception exception);
}
}
27 changes: 7 additions & 20 deletions src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,14 @@

namespace Microsoft.Extensions.Logging;

internal static class LoggingExtensions
internal static partial class LoggingExtensions
{
private static readonly Action<ILogger, Exception> _tokenValidationFailed = LoggerMessage.Define(
eventId: new EventId(1, "TokenValidationFailed"),
logLevel: LogLevel.Information,
formatString: "Failed to validate the token.");
private static readonly Action<ILogger, Exception?> _tokenValidationSucceeded = LoggerMessage.Define(
eventId: new EventId(2, "TokenValidationSucceeded"),
logLevel: LogLevel.Debug,
formatString: "Successfully validated the token.");
private static readonly Action<ILogger, Exception> _errorProcessingMessage = LoggerMessage.Define(
eventId: new EventId(3, "ProcessingMessageFailed"),
logLevel: LogLevel.Error,
formatString: "Exception occurred while processing message.");
[LoggerMessage(1, LogLevel.Information, "Failed to validate the token.", EventName = "TokenValidationFailed")]
public static partial void TokenValidationFailed(this ILogger logger, Exception ex);

public static void TokenValidationFailed(this ILogger logger, Exception ex)
=> _tokenValidationFailed(logger, ex);
[LoggerMessage(2, LogLevel.Debug, "Successfully validated the token.", EventName = "TokenValidationSucceeded")]
public static partial void TokenValidationSucceeded(this ILogger logger);

public static void TokenValidationSucceeded(this ILogger logger)
=> _tokenValidationSucceeded(logger, null);

public static void ErrorProcessingMessage(this ILogger logger, Exception ex)
=> _errorProcessingMessage(logger, ex);
[LoggerMessage(3, LogLevel.Error, "Exception occurred while processing message.", EventName = "ProcessingMessageFailed")]
public static partial void ErrorProcessingMessage(this ILogger logger, Exception ex);
}
74 changes: 17 additions & 57 deletions src/Servers/HttpSys/src/HttpSysListener.Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,70 +7,30 @@ namespace Microsoft.AspNetCore.Server.HttpSys;

internal partial class HttpSysListener
{
private static class Log
private static partial class Log
{
private static readonly Action<ILogger, Exception?> _listenerDisposeError =
LoggerMessage.Define(LogLevel.Error, LoggerEventIds.ListenerDisposeError, "Dispose");
[LoggerMessage(LoggerEventIds.ListenerDisposeError, LogLevel.Error, "Dispose", EventName = "ListenerDisposeError")]
public static partial void ListenerDisposeError(ILogger logger, Exception exception);

private static readonly Action<ILogger, Exception?> _listenerDisposing =
LoggerMessage.Define(LogLevel.Trace, LoggerEventIds.ListenerDisposing, "Disposing the listener.");
[LoggerMessage(LoggerEventIds.ListenerDisposing, LogLevel.Trace, "Disposing the listener.", EventName = "ListenerDisposing")]
public static partial void ListenerDisposing(ILogger logger);

private static readonly Action<ILogger, Exception?> _httpSysListenerCtorError =
LoggerMessage.Define(LogLevel.Error, LoggerEventIds.HttpSysListenerCtorError, ".Ctor");
[LoggerMessage(LoggerEventIds.HttpSysListenerCtorError, LogLevel.Error, ".Ctor", EventName = "HttpSysListenerCtorError")]
public static partial void HttpSysListenerCtorError(ILogger logger, Exception exception);

private static readonly Action<ILogger, Exception?> _listenerStartError =
LoggerMessage.Define(LogLevel.Error, LoggerEventIds.ListenerStartError, "Start");
[LoggerMessage(LoggerEventIds.ListenerStartError, LogLevel.Error, "Start", EventName = "ListenerStartError")]
public static partial void ListenerStartError(ILogger logger, Exception exception);

private static readonly Action<ILogger, Exception?> _listenerStarting =
LoggerMessage.Define(LogLevel.Trace, LoggerEventIds.ListenerStarting, "Starting the listener.");
[LoggerMessage(LoggerEventIds.ListenerStarting, LogLevel.Trace, "Starting the listener.", EventName = "ListenerStarting")]
public static partial void ListenerStarting(ILogger logger);

private static readonly Action<ILogger, Exception?> _listenerStopError =
LoggerMessage.Define(LogLevel.Error, LoggerEventIds.ListenerStopError, "Stop");
[LoggerMessage(LoggerEventIds.ListenerStopError, LogLevel.Error, "Stop", EventName = "ListenerStopError")]
public static partial void ListenerStopError(ILogger logger, Exception exception);

private static readonly Action<ILogger, Exception?> _listenerStopping =
LoggerMessage.Define(LogLevel.Trace, LoggerEventIds.ListenerStopping, "Stopping the listener.");
[LoggerMessage(LoggerEventIds.ListenerStopping, LogLevel.Trace, "Stopping the listener.", EventName = "ListenerStopping")]
public static partial void ListenerStopping(ILogger logger);

private static readonly Action<ILogger, ulong, Exception?> _requestValidationFailed =
LoggerMessage.Define<ulong>(LogLevel.Error, LoggerEventIds.RequestValidationFailed, "Error validating request {RequestId}");

public static void ListenerDisposeError(ILogger logger, Exception exception)
{
_listenerDisposeError(logger, exception);
}

public static void ListenerDisposing(ILogger logger)
{
_listenerDisposing(logger, null);
}

public static void HttpSysListenerCtorError(ILogger logger, Exception exception)
{
_httpSysListenerCtorError(logger, exception);
}

public static void ListenerStartError(ILogger logger, Exception exception)
{
_listenerStartError(logger, exception);
}

public static void ListenerStarting(ILogger logger)
{
_listenerStarting(logger, null);
}

public static void ListenerStopError(ILogger logger, Exception exception)
{
_listenerStopError(logger, exception);
}

public static void ListenerStopping(ILogger logger)
{
_listenerStopping(logger, null);
}

public static void RequestValidationFailed(ILogger logger, Exception exception, ulong requestId)
{
_requestValidationFailed(logger, requestId, exception);
}
[LoggerMessage(LoggerEventIds.RequestValidationFailed, LogLevel.Error, "Error validating request {RequestId}", EventName = "RequestValidationFailed")]
public static partial void RequestValidationFailed(ILogger logger, Exception exception, ulong requestId);
}
}
Loading