From e01773ab269420c3b9cdb66b43621331adc670ce Mon Sep 17 00:00:00 2001 From: Pranav K Date: Thu, 17 Feb 2022 20:18:06 -0800 Subject: [PATCH] Use LoggerMessageAttribute in more places * Servers * Antiforgery * Missed Blazor and Security projects --- .../Internal/AntiforgeryLoggerExtensions.cs | 112 ++++-------------- .../src/Rendering/WebAssemblyRenderer.cs | 27 +---- .../JwtBearer/src/LoggingExtensions.cs | 27 ++--- .../HttpSys/src/HttpSysListener.Log.cs | 74 +++--------- src/Servers/HttpSys/src/LoggerEventIds.cs | 98 ++++++++------- src/Servers/HttpSys/src/MessagePump.Log.cs | 80 +++++-------- .../NativeInterop/DisconnectListener.Log.cs | 56 ++------- .../HttpSys/src/NativeInterop/RequestQueue.cs | 13 +- .../HttpSys/src/NativeInterop/UrlGroup.Log.cs | 38 ++---- .../RequestProcessing/ClientCertLoader.Log.cs | 20 +--- .../HttpSys/src/RequestProcessing/Request.cs | 13 +- .../RequestProcessing/RequestContext.Log.cs | 29 ++--- .../RequestProcessing/RequestContextLog.cs | 29 ++--- .../RequestProcessing/RequestStream.Log.cs | 29 ++--- .../src/RequestProcessing/ResponseBody.cs | 76 +++--------- .../ResponseStreamAsyncResult.Log.cs | 29 ++--- .../IIS/IIS/src/Core/IISHttpContext.Log.cs | 39 ++---- 17 files changed, 219 insertions(+), 570 deletions(-) diff --git a/src/Antiforgery/src/Internal/AntiforgeryLoggerExtensions.cs b/src/Antiforgery/src/Internal/AntiforgeryLoggerExtensions.cs index c8035c1badff..00ba5d326f92 100644 --- a/src/Antiforgery/src/Internal/AntiforgeryLoggerExtensions.cs +++ b/src/Antiforgery/src/Internal/AntiforgeryLoggerExtensions.cs @@ -5,103 +5,35 @@ namespace Microsoft.AspNetCore.Antiforgery; -internal static class AntiforgeryLoggerExtensions +internal static partial class AntiforgeryLoggerExtensions { - private static readonly Action _failedToDeserialzeTokens; - private static readonly Action _validationFailed; - private static readonly Action _validated; - private static readonly Action _missingCookieToken; - private static readonly Action _missingRequestToken; - private static readonly Action _newCookieToken; - private static readonly Action _reusedCookieToken; - private static readonly Action _tokenDeserializeException; - private static readonly Action _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( - 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( - LogLevel.Warning, - new EventId(3, "MissingCookieToken"), - "The required antiforgery cookie '{CookieName}' is not present."); - _missingRequestToken = LoggerMessage.Define( - 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); } diff --git a/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs b/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs index 8e766eaa9a6c..0f13779e57c9 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Rendering; /// Provides mechanisms for rendering instances in a /// web browser, dispatching events to them, and refreshing the UI as required. /// -internal class WebAssemblyRenderer : WebRenderer +internal partial class WebAssemblyRenderer : WebRenderer { private readonly ILogger _logger; @@ -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 _unhandledExceptionRenderingComponent = LoggerMessage.Define( - 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); } } diff --git a/src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs b/src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs index 709689f1a631..c13da34abf3f 100644 --- a/src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs +++ b/src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs @@ -3,27 +3,14 @@ namespace Microsoft.Extensions.Logging; -internal static class LoggingExtensions +internal static partial class LoggingExtensions { - private static readonly Action _tokenValidationFailed = LoggerMessage.Define( - eventId: new EventId(1, "TokenValidationFailed"), - logLevel: LogLevel.Information, - formatString: "Failed to validate the token."); - private static readonly Action _tokenValidationSucceeded = LoggerMessage.Define( - eventId: new EventId(2, "TokenValidationSucceeded"), - logLevel: LogLevel.Debug, - formatString: "Successfully validated the token."); - private static readonly Action _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); } diff --git a/src/Servers/HttpSys/src/HttpSysListener.Log.cs b/src/Servers/HttpSys/src/HttpSysListener.Log.cs index 000f211fc63c..d50290185c9a 100644 --- a/src/Servers/HttpSys/src/HttpSysListener.Log.cs +++ b/src/Servers/HttpSys/src/HttpSysListener.Log.cs @@ -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 _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 _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 _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 _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 _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 _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 _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 _requestValidationFailed = - LoggerMessage.Define(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); } } diff --git a/src/Servers/HttpSys/src/LoggerEventIds.cs b/src/Servers/HttpSys/src/LoggerEventIds.cs index 6c55514222c9..f803811a7970 100644 --- a/src/Servers/HttpSys/src/LoggerEventIds.cs +++ b/src/Servers/HttpSys/src/LoggerEventIds.cs @@ -1,58 +1,56 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Microsoft.Extensions.Logging; - namespace Microsoft.AspNetCore.Server.HttpSys; internal static class LoggerEventIds { - public static readonly EventId HttpSysListenerCtorError = new EventId(1, "HttpSysListenerCtorError"); - public static readonly EventId BindingToDefault = new EventId(2, "BindingToDefault"); - public static readonly EventId ClearedPrefixes = new EventId(3, "ClearedPrefixes"); - public static readonly EventId AcceptErrorStopping = new EventId(4, "AcceptErrorStopping"); - public static readonly EventId AcceptError = new EventId(5, "AcceptError"); - public static readonly EventId RequestProcessError = new EventId(6, "RequestProcessError"); - public static readonly EventId RequestsDrained = new EventId(7, "RequestsDrained"); - public static readonly EventId StopCancelled = new EventId(8, "StopCancelled"); - public static readonly EventId WaitingForRequestsToDrain = new EventId(9, "WaitingForRequestsToDrain"); - public static readonly EventId DisconnectRegistrationError = new EventId(10, "DisconnectRegistrationError"); - public static readonly EventId RegisterDisconnectListener = new EventId(11, "RegisterDisconnectListener"); - public static readonly EventId UnknownDisconnectError = new EventId(12, "UnknownDisconnectError"); - public static readonly EventId DisconnectHandlerError = new EventId(13, "DisconnectHandlerError"); - public static readonly EventId ListenerStarting = new EventId(14, "ListenerStarting"); - public static readonly EventId ListenerDisposeError = new EventId(15, "ListenerDisposeError"); - public static readonly EventId RequestListenerProcessError = new EventId(16, "RequestListenerProcessError"); - public static readonly EventId AttachedToQueue = new EventId(17, "AttachedToQueue"); - public static readonly EventId SetUrlPropertyError = new EventId(18, "SetUrlPropertyError"); - public static readonly EventId RegisteringPrefix = new EventId(19, "RegisteringPrefix"); - public static readonly EventId UnregisteringPrefix = new EventId(20, "UnregisteringPrefix"); - public static readonly EventId CloseUrlGroupError = new EventId(21, "CloseUrlGroupError"); - public static readonly EventId ChannelBindingUnsupported = new EventId(22, "ChannelBindingUnSupported"); - public static readonly EventId ChannelBindingMissing = new EventId(23, "ChannelBindingMissing"); - public static readonly EventId RequestError = new EventId(24, "RequestError"); - public static readonly EventId ErrorInReadingCertificate = new EventId(25, "ErrorInReadingCertificate"); - public static readonly EventId ChannelBindingNeedsHttps = new EventId(26, "ChannelBindingNeedsHttps"); - public static readonly EventId ChannelBindingRetrieved = new EventId(27, "ChannelBindingRetrived"); - public static readonly EventId AbortError = new EventId(28, "AbortError"); - public static readonly EventId ErrorWhileRead = new EventId(29, "ErrorWhileRead"); - public static readonly EventId ErrorWhenReadBegun = new EventId(30, "ErrorWhenReadBegun"); - public static readonly EventId ErrorWhenReadAsync = new EventId(31, "ErrorWhenReadAsync"); - public static readonly EventId ErrorWhenFlushAsync = new EventId(32, "ErrorWhenFlushAsync"); - public static readonly EventId FewerBytesThanExpected = new EventId(33, "FewerBytesThanExpected"); - public static readonly EventId WriteError = new EventId(34, "WriteError"); - public static readonly EventId WriteErrorIgnored = new EventId(35, "WriteFlushedIgnored"); - public static readonly EventId WriteFlushCancelled = new EventId(36, "WriteFlushCancelled"); - public static readonly EventId ClearedAddresses = new EventId(37, "ClearedAddresses"); - public static readonly EventId FileSendAsyncError = new EventId(38, "FileSendAsyncError"); - public static readonly EventId FileSendAsyncCancelled = new EventId(39, "FileSendAsyncCancelled"); - public static readonly EventId FileSendAsyncErrorIgnored = new EventId(40, "FileSendAsyncErrorIgnored"); - public static readonly EventId WriteCancelled = new EventId(41, "WriteCancelled"); - public static readonly EventId ListenerStopping = new EventId(42, "ListenerStopping"); - public static readonly EventId ListenerStartError = new EventId(43, "ListenerStartError"); - public static readonly EventId DisconnectTriggered = new EventId(44, "DisconnectTriggered"); - public static readonly EventId ListenerStopError = new EventId(45, "ListenerStopError"); - public static readonly EventId ListenerDisposing = new EventId(46, "ListenerDisposing"); - public static readonly EventId RequestValidationFailed = new EventId(47, "RequestValidationFailed"); - public static readonly EventId CreateDisconnectTokenError = new EventId(48, "CreateDisconnectTokenError"); + public const int HttpSysListenerCtorError = 1; + public const int BindingToDefault = 2; + public const int ClearedPrefixes = 3; + public const int AcceptErrorStopping = 4; + public const int AcceptError = 5; + public const int RequestProcessError = 6; + public const int RequestsDrained = 7; + public const int StopCancelled = 8; + public const int WaitingForRequestsToDrain = 9; + public const int DisconnectRegistrationError = 10; + public const int RegisterDisconnectListener = 11; + public const int UnknownDisconnectError = 12; + public const int DisconnectHandlerError = 13; + public const int ListenerStarting = 14; + public const int ListenerDisposeError = 15; + public const int RequestListenerProcessError = 16; + public const int AttachedToQueue = 17; + public const int SetUrlPropertyError = 18; + public const int RegisteringPrefix = 19; + public const int UnregisteringPrefix = 20; + public const int CloseUrlGroupError = 21; + public const int ChannelBindingUnsupported = 22; + public const int ChannelBindingMissing = 23; + public const int RequestError = 24; + public const int ErrorInReadingCertificate = 25; + public const int ChannelBindingNeedsHttps = 26; + public const int ChannelBindingRetrieved = 27; + public const int AbortError = 28; + public const int ErrorWhileRead = 29; + public const int ErrorWhenReadBegun = 30; + public const int ErrorWhenReadAsync = 31; + public const int ErrorWhenFlushAsync = 32; + public const int FewerBytesThanExpected = 33; + public const int WriteError = 34; + public const int WriteErrorIgnored = 35; + public const int WriteFlushCancelled = 36; + public const int ClearedAddresses = 37; + public const int FileSendAsyncError = 38; + public const int FileSendAsyncCancelled = 39; + public const int FileSendAsyncErrorIgnored = 40; + public const int WriteCancelled = 41; + public const int ListenerStopping = 42; + public const int ListenerStartError = 43; + public const int DisconnectTriggered = 44; + public const int ListenerStopError = 45; + public const int ListenerDisposing = 46; + public const int RequestValidationFailed = 47; + public const int CreateDisconnectTokenError = 48; } diff --git a/src/Servers/HttpSys/src/MessagePump.Log.cs b/src/Servers/HttpSys/src/MessagePump.Log.cs index 1e4ab52ab49a..b44bf6d3615b 100644 --- a/src/Servers/HttpSys/src/MessagePump.Log.cs +++ b/src/Servers/HttpSys/src/MessagePump.Log.cs @@ -9,78 +9,52 @@ namespace Microsoft.AspNetCore.Server.HttpSys; internal partial class MessagePump { - private static class Log + private static partial class Log { - private static readonly LogDefineOptions SkipEnabledCheckLogOptions = new() { SkipEnabledCheck = true }; + [LoggerMessage(LoggerEventIds.AcceptError, LogLevel.Error, "Failed to accept a request.", EventName = "AcceptError")] + public static partial void AcceptError(ILogger logger, Exception exception); - private static readonly Action _acceptError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.AcceptError, "Failed to accept a request."); + [LoggerMessage(LoggerEventIds.AcceptErrorStopping, LogLevel.Debug, "Failed to accept a request, the server is stopping.", EventName = "AcceptErrorStopping")] + public static partial void AcceptErrorStopping(ILogger logger, Exception exception); - private static readonly Action _acceptErrorStopping = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.AcceptErrorStopping, "Failed to accept a request, the server is stopping."); - - private static readonly Action _bindingToDefault = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.BindingToDefault, $"No listening endpoints were configured. Binding to {Constants.DefaultServerAddress} by default."); - - private static readonly Action _clearedAddresses = - LoggerMessage.Define(LogLevel.Warning, LoggerEventIds.ClearedAddresses, $"Overriding address(es) '{{ServerAddresses)}}'. Binding to endpoints added to {nameof(HttpSysOptions.UrlPrefixes)} instead.", SkipEnabledCheckLogOptions); - - private static readonly Action _clearedPrefixes = - LoggerMessage.Define(LogLevel.Warning, LoggerEventIds.ClearedPrefixes, $"Overriding endpoints added to {nameof(HttpSysOptions.UrlPrefixes)} since {nameof(IServerAddressesFeature.PreferHostingUrls)} is set to true. Binding to address(es) '{{ServerAddresses}}' instead.", SkipEnabledCheckLogOptions); - - private static readonly Action _requestListenerProcessError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.RequestListenerProcessError, "ProcessRequestAsync"); - - private static readonly Action _stopCancelled = - LoggerMessage.Define(LogLevel.Information, LoggerEventIds.StopCancelled, "Canceled, terminating {OutstandingRequests} request(s)."); - - private static readonly Action _waitingForRequestsToDrain = - LoggerMessage.Define(LogLevel.Information, LoggerEventIds.WaitingForRequestsToDrain, "Stopping, waiting for {OutstandingRequests} request(s) to drain."); - - public static void AcceptError(ILogger logger, Exception exception) - { - _acceptError(logger, exception); - } - - public static void AcceptErrorStopping(ILogger logger, Exception exception) - { - _acceptErrorStopping(logger, exception); - } - - public static void BindingToDefault(ILogger logger) - { - _bindingToDefault(logger, null); - } + [LoggerMessage(LoggerEventIds.BindingToDefault, LogLevel.Debug, $"No listening endpoints were configured. Binding to {Constants.DefaultServerAddress} by default.", EventName = "BindingToDefault")] + public static partial void BindingToDefault(ILogger logger); public static void ClearedAddresses(ILogger logger, ICollection serverAddresses) { if (logger.IsEnabled(LogLevel.Warning)) { - _clearedAddresses(logger, string.Join(", ", serverAddresses), null); + ClearedAddressesCore(logger, string.Join(", ", serverAddresses)); } } + [LoggerMessage(LoggerEventIds.ClearedAddresses, LogLevel.Warning, + $"Overriding address(es) '{{ServerAddresses}}'. Binding to endpoints added to {nameof(HttpSysOptions.UrlPrefixes)} instead.", + EventName = "ClearedAddresses", + SkipEnabledCheck = true)] + private static partial void ClearedAddressesCore(ILogger logger, string serverAddresses); + public static void ClearedPrefixes(ILogger logger, ICollection serverAddresses) { if (logger.IsEnabled(LogLevel.Warning)) { - _clearedPrefixes(logger, string.Join(", ", serverAddresses), null); + ClearedPrefixesCore(logger, string.Join(", ", serverAddresses)); } } - public static void RequestListenerProcessError(ILogger logger, Exception exception) - { - _requestListenerProcessError(logger, exception); - } + [LoggerMessage(LoggerEventIds.ClearedPrefixes, LogLevel.Warning, + $"Overriding endpoints added to {nameof(HttpSysOptions.UrlPrefixes)} since {nameof(IServerAddressesFeature.PreferHostingUrls)} is set to true. Binding to address(es) '{{ServerAddresses}}' instead.", + EventName = "ClearedPrefixes", + SkipEnabledCheck = true)] + private static partial void ClearedPrefixesCore(ILogger logger, string serverAddresses); - public static void StopCancelled(ILogger logger, int outstandingRequests) - { - _stopCancelled(logger, outstandingRequests, null); - } + [LoggerMessage(LoggerEventIds.RequestListenerProcessError, LogLevel.Error, "ProcessRequestAsync", EventName = "RequestListenerProcessError")] + public static partial void RequestListenerProcessError(ILogger logger, Exception exception); - public static void WaitingForRequestsToDrain(ILogger logger, int outstandingRequests) - { - _waitingForRequestsToDrain(logger, outstandingRequests, null); - } + [LoggerMessage(LoggerEventIds.StopCancelled, LogLevel.Information, "Canceled, terminating {OutstandingRequests} request(s).", EventName = "StopCancelled")] + public static partial void StopCancelled(ILogger logger, int outstandingRequests); + + [LoggerMessage(LoggerEventIds.WaitingForRequestsToDrain, LogLevel.Information, "Stopping, waiting for {OutstandingRequests} request(s) to drain.", EventName = "WaitingForRequestsToDrain")] + public static partial void WaitingForRequestsToDrain(ILogger logger, int outstandingRequests); } } diff --git a/src/Servers/HttpSys/src/NativeInterop/DisconnectListener.Log.cs b/src/Servers/HttpSys/src/NativeInterop/DisconnectListener.Log.cs index 8d3c7e944e61..bb2c5be4ff55 100644 --- a/src/Servers/HttpSys/src/NativeInterop/DisconnectListener.Log.cs +++ b/src/Servers/HttpSys/src/NativeInterop/DisconnectListener.Log.cs @@ -7,54 +7,24 @@ namespace Microsoft.AspNetCore.Server.HttpSys; internal partial class DisconnectListener { - private static class Log + private static partial class Log { - private static readonly Action _disconnectHandlerError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.DisconnectHandlerError, "CreateDisconnectToken Callback"); + [LoggerMessage(LoggerEventIds.DisconnectHandlerError, LogLevel.Error, "CreateDisconnectToken Callback", EventName = "DisconnectHandlerError")] + public static partial void DisconnectHandlerError(ILogger logger, Exception exception); - private static readonly Action _createDisconnectTokenError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.CreateDisconnectTokenError, "CreateDisconnectToken"); + [LoggerMessage(LoggerEventIds.DisconnectRegistrationError, LogLevel.Error, "Unable to register for disconnect notifications.", EventName = "DisconnectRegistrationError")] + public static partial void DisconnectRegistrationError(ILogger logger, Exception exception); - private static readonly Action _disconnectRegistrationError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.DisconnectRegistrationError, "Unable to register for disconnect notifications."); + [LoggerMessage(LoggerEventIds.CreateDisconnectTokenError, LogLevel.Error, "CreateDisconnectToken", EventName = "CreateDisconnectTokenError")] + public static partial void CreateDisconnectTokenError(ILogger logger, Exception exception); - private static readonly Action _disconnectTriggered = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.DisconnectTriggered, "CreateDisconnectToken; http.sys disconnect callback fired for connection ID: {ConnectionId}"); + [LoggerMessage(LoggerEventIds.DisconnectTriggered, LogLevel.Debug, "CreateDisconnectToken; http.sys disconnect callback fired for connection ID: {ConnectionId}", EventName = "DisconnectTriggered")] + public static partial void DisconnectTriggered(ILogger logger, ulong connectionId); - private static readonly Action _registerDisconnectListener = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.RegisterDisconnectListener, "CreateDisconnectToken; Registering connection for disconnect for connection ID: {ConnectionId}"); + [LoggerMessage(LoggerEventIds.RegisterDisconnectListener, LogLevel.Debug, "CreateDisconnectToken; Registering connection for disconnect for connection ID: {ConnectionId}", EventName = "RegisterDisconnectListener")] + public static partial void RegisterDisconnectListener(ILogger logger, ulong connectionId); - private static readonly Action _unknownDisconnectError = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.UnknownDisconnectError, "HttpWaitForDisconnectEx"); - - public static void DisconnectHandlerError(ILogger logger, Exception exception) - { - _disconnectHandlerError(logger, exception); - } - - public static void DisconnectRegistrationError(ILogger logger, Exception exception) - { - _disconnectRegistrationError(logger, exception); - } - - public static void CreateDisconnectTokenError(ILogger logger, Exception exception) - { - _createDisconnectTokenError(logger, exception); - } - - public static void DisconnectTriggered(ILogger logger, ulong connectionId) - { - _disconnectTriggered(logger, connectionId, null); - } - - public static void RegisterDisconnectListener(ILogger logger, ulong connectionId) - { - _registerDisconnectListener(logger, connectionId, null); - } - - public static void UnknownDisconnectError(ILogger logger, Exception exception) - { - _unknownDisconnectError(logger, exception); - } + [LoggerMessage(LoggerEventIds.UnknownDisconnectError, LogLevel.Debug, "HttpWaitForDisconnectEx", EventName = "UnknownDisconnectError")] + public static partial void UnknownDisconnectError(ILogger logger, Exception exception); } } diff --git a/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs b/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs index 64fe54bc3114..353ea0ebf8a1 100644 --- a/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs +++ b/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -internal class RequestQueue +internal sealed partial class RequestQueue { private static readonly int BindingInfoSize = Marshal.SizeOf(); @@ -206,14 +206,9 @@ private void CheckDisposed() } } - private static class Log + private static partial class Log { - private static readonly Action _attachedToQueue = - LoggerMessage.Define(LogLevel.Information, LoggerEventIds.AttachedToQueue, "Attached to an existing request queue '{RequestQueueName}', some options do not apply."); - - public static void AttachedToQueue(ILogger logger, string? requestQueueName) - { - _attachedToQueue(logger, requestQueueName, null); - } + [LoggerMessage(LoggerEventIds.AttachedToQueue, LogLevel.Information, "Attached to an existing request queue '{RequestQueueName}', some options do not apply.", EventName = "AttachedToQueue")] + public static partial void AttachedToQueue(ILogger logger, string? requestQueueName); } } diff --git a/src/Servers/HttpSys/src/NativeInterop/UrlGroup.Log.cs b/src/Servers/HttpSys/src/NativeInterop/UrlGroup.Log.cs index 474811b25498..f7103f03ecc2 100644 --- a/src/Servers/HttpSys/src/NativeInterop/UrlGroup.Log.cs +++ b/src/Servers/HttpSys/src/NativeInterop/UrlGroup.Log.cs @@ -7,38 +7,18 @@ namespace Microsoft.AspNetCore.Server.HttpSys; internal partial class UrlGroup { - private static class Log + private static partial class Log { - private static readonly Action _closeUrlGroupError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.CloseUrlGroupError, "HttpCloseUrlGroup; Result: {StatusCode}"); + [LoggerMessage(LoggerEventIds.CloseUrlGroupError, LogLevel.Error, "HttpCloseUrlGroup; Result: {StatusCode}", EventName = "CloseUrlGroupError")] + public static partial void CloseUrlGroupError(ILogger logger, uint statusCode); - private static readonly Action _registeringPrefix = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.RegisteringPrefix, "Listening on prefix: {UriPrefix}"); + [LoggerMessage(LoggerEventIds.RegisteringPrefix, LogLevel.Debug, "Listening on prefix: {UriPrefix}", EventName = "RegisteringPrefix")] + public static partial void RegisteringPrefix(ILogger logger, string uriPrefix); - private static readonly Action _setUrlPropertyError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.SetUrlPropertyError, "SetUrlGroupProperty"); + [LoggerMessage(LoggerEventIds.SetUrlPropertyError, LogLevel.Error, "SetUrlGroupProperty", EventName = "SetUrlPropertyError")] + public static partial void SetUrlPropertyError(ILogger logger, Exception exception); - private static readonly Action _unregisteringPrefix = - LoggerMessage.Define(LogLevel.Information, LoggerEventIds.UnregisteringPrefix, "Stop listening on prefix: {UriPrefix}"); - - public static void CloseUrlGroupError(ILogger logger, uint statusCode) - { - _closeUrlGroupError(logger, statusCode, null); - } - - public static void RegisteringPrefix(ILogger logger, string uriPrefix) - { - _registeringPrefix(logger, uriPrefix, null); - } - - public static void SetUrlPropertyError(ILogger logger, Exception exception) - { - _setUrlPropertyError(logger, exception); - } - - public static void UnregisteringPrefix(ILogger logger, string uriPrefix) - { - _unregisteringPrefix(logger, uriPrefix, null); - } + [LoggerMessage(LoggerEventIds.UnregisteringPrefix, LogLevel.Information, "Stop listening on prefix: {UriPrefix}", EventName = "UnregisteringPrefix")] + public static partial void UnregisteringPrefix(ILogger logger, string uriPrefix); } } diff --git a/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.Log.cs b/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.Log.cs index f70d2b6c38de..85441bc6d077 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.Log.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/ClientCertLoader.Log.cs @@ -7,22 +7,12 @@ namespace Microsoft.AspNetCore.Server.HttpSys; internal partial class ClientCertLoader { - private static class Log + private static partial class Log { - private static readonly Action _channelBindingMissing = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.ChannelBindingMissing, "GetChannelBindingFromTls"); + [LoggerMessage(LoggerEventIds.ChannelBindingMissing, LogLevel.Error, "GetChannelBindingFromTls", EventName = "ChannelBindingMissing")] + public static partial void ChannelBindingMissing(ILogger logger, Exception exception); - private static readonly Action _channelBindingUnsupported = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.ChannelBindingUnsupported, "GetChannelBindingFromTls; Channel binding is not supported."); - - public static void ChannelBindingMissing(ILogger logger, Exception exception) - { - _channelBindingMissing(logger, exception); - } - - public static void ChannelBindingUnsupported(ILogger logger) - { - _channelBindingUnsupported(logger, null); - } + [LoggerMessage(LoggerEventIds.ChannelBindingUnsupported, LogLevel.Error, "GetChannelBindingFromTls; Channel binding is not supported.", EventName = "ChannelBindingUnsupported")] + public static partial void ChannelBindingUnsupported(ILogger logger); } } diff --git a/src/Servers/HttpSys/src/RequestProcessing/Request.cs b/src/Servers/HttpSys/src/RequestProcessing/Request.cs index b3dfc83e1c06..334b15b8f51f 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/Request.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/Request.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -internal sealed class Request +internal sealed partial class Request { private X509Certificate2? _clientCert; // TODO: https://github.com/aspnet/HttpSysServer/issues/231 @@ -451,14 +451,9 @@ internal void SwitchToOpaqueMode() _nativeStream.SwitchToOpaqueMode(); } - private static class Log + private static partial class Log { - private static readonly Action _errorInReadingCertificate = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.ErrorInReadingCertificate, "An error occurred reading the client certificate."); - - public static void ErrorInReadingCertificate(ILogger logger, Exception exception) - { - _errorInReadingCertificate(logger, exception); - } + [LoggerMessage(LoggerEventIds.ErrorInReadingCertificate, LogLevel.Debug, "An error occurred reading the client certificate.", EventName = "ErrorInReadingCertificate")] + public static partial void ErrorInReadingCertificate(ILogger logger, Exception exception); } } diff --git a/src/Servers/HttpSys/src/RequestProcessing/RequestContext.Log.cs b/src/Servers/HttpSys/src/RequestProcessing/RequestContext.Log.cs index 2f70a39763c1..2c587b98a401 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/RequestContext.Log.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/RequestContext.Log.cs @@ -7,30 +7,15 @@ namespace Microsoft.AspNetCore.Server.HttpSys; internal partial class RequestContext { - private static class Log + private static partial class Log { - private static readonly Action _abortError = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.AbortError, "Abort"); + [LoggerMessage(LoggerEventIds.AbortError, LogLevel.Debug, "Abort", EventName = "AbortError")] + public static partial void AbortError(ILogger logger, Exception exception); - private static readonly Action _channelBindingNeedsHttps = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.ChannelBindingNeedsHttps, "TryGetChannelBinding; Channel binding requires HTTPS."); + [LoggerMessage(LoggerEventIds.ChannelBindingNeedsHttps, LogLevel.Debug, "TryGetChannelBinding; Channel binding requires HTTPS.", EventName = "ChannelBindingNeedsHttps")] + public static partial void ChannelBindingNeedsHttps(ILogger logger); - private static readonly Action _channelBindingRetrieved = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.ChannelBindingRetrieved, "Channel binding retrieved."); - - public static void AbortError(ILogger logger, Exception exception) - { - _abortError(logger, exception); - } - - public static void ChannelBindingNeedsHttps(ILogger logger) - { - _channelBindingNeedsHttps(logger, null); - } - - public static void ChannelBindingRetrieved(ILogger logger) - { - _channelBindingRetrieved(logger, null); - } + [LoggerMessage(LoggerEventIds.ChannelBindingRetrieved, LogLevel.Debug, "Channel binding retrieved.", EventName = "ChannelBindingRetrieved")] + public static partial void ChannelBindingRetrieved(ILogger logger); } } diff --git a/src/Servers/HttpSys/src/RequestProcessing/RequestContextLog.cs b/src/Servers/HttpSys/src/RequestProcessing/RequestContextLog.cs index e2d06b537375..453be47afc4c 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/RequestContextLog.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/RequestContextLog.cs @@ -5,29 +5,14 @@ namespace Microsoft.AspNetCore.Server.HttpSys; -internal static class RequestContextLog +internal static partial class RequestContextLog { - private static readonly Action _requestError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.RequestError, "ProcessRequestAsync"); + [LoggerMessage(LoggerEventIds.RequestError, LogLevel.Error, "ProcessRequestAsync", EventName = "RequestError")] + public static partial void RequestError(ILogger logger, Exception exception); - private static readonly Action _requestProcessError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.RequestProcessError, "ProcessRequestAsync"); + [LoggerMessage(LoggerEventIds.RequestProcessError, LogLevel.Error, "ProcessRequestAsync", EventName = "RequestProcessError")] + public static partial void RequestProcessError(ILogger logger, Exception exception); - private static readonly Action _requestsDrained = - LoggerMessage.Define(LogLevel.Information, LoggerEventIds.RequestsDrained, "All requests drained."); - - public static void RequestError(ILogger logger, Exception exception) - { - _requestError(logger, exception); - } - - public static void RequestProcessError(ILogger logger, Exception exception) - { - _requestProcessError(logger, exception); - } - - public static void RequestsDrained(ILogger logger) - { - _requestsDrained(logger, null); - } + [LoggerMessage(LoggerEventIds.RequestsDrained, LogLevel.Information, "All requests drained.", EventName = "RequestsDrained")] + public static partial void RequestsDrained(ILogger logger); } diff --git a/src/Servers/HttpSys/src/RequestProcessing/RequestStream.Log.cs b/src/Servers/HttpSys/src/RequestProcessing/RequestStream.Log.cs index 7be154d75df9..454da123fb3d 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/RequestStream.Log.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/RequestStream.Log.cs @@ -7,30 +7,15 @@ namespace Microsoft.AspNetCore.Server.HttpSys; internal partial class RequestStream { - private static class Log + private static partial class Log { - private static readonly Action _errorWhenReadAsync = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.ErrorWhenReadAsync, "ReadAsync"); + [LoggerMessage(LoggerEventIds.ErrorWhenReadAsync, LogLevel.Debug, "ReadAsync", EventName = "ErrorWhenReadAsync")] + public static partial void ErrorWhenReadAsync(ILogger logger, Exception exception); - private static readonly Action _errorWhenReadBegun = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.ErrorWhenReadBegun, "BeginRead"); + [LoggerMessage(LoggerEventIds.ErrorWhenReadBegun, LogLevel.Debug, "BeginRead", EventName = "ErrorWhenReadBegun")] + public static partial void ErrorWhenReadBegun(ILogger logger, Exception exception); - private static readonly Action _errorWhileRead = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.ErrorWhileRead, "Read"); - - public static void ErrorWhenReadAsync(ILogger logger, Exception exception) - { - _errorWhenReadAsync(logger, exception); - } - - public static void ErrorWhenReadBegun(ILogger logger, Exception exception) - { - _errorWhenReadBegun(logger, exception); - } - - public static void ErrorWhileRead(ILogger logger, Exception exception) - { - _errorWhileRead(logger, exception); - } + [LoggerMessage(LoggerEventIds.ErrorWhileRead, LogLevel.Debug, "Read", EventName = "ErrorWhileRead")] + public static partial void ErrorWhileRead(ILogger logger, Exception exception); } } diff --git a/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs b/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs index dad563a428ab..7a5f0dce182b 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/ResponseBody.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; #pragma warning disable CA1844 // Provide memory-based overrides of async methods when subclassing 'Stream'. Fixing this is too gnarly. -internal class ResponseBody : Stream +internal sealed partial class ResponseBody : Stream #pragma warning restore CA1844 { private readonly RequestContext _requestContext; @@ -732,70 +732,30 @@ private void CheckDisposed() } } - private static class Log + private static partial class Log { - private static readonly Action _fewerBytesThanExpected = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.FewerBytesThanExpected, "ResponseStream::Dispose; Fewer bytes were written than were specified in the Content-Length."); + [LoggerMessage(LoggerEventIds.FewerBytesThanExpected, LogLevel.Error, "ResponseStream::Dispose; Fewer bytes were written than were specified in the Content-Length.", EventName = "FewerBytesThanExpected")] + public static partial void FewerBytesThanExpected(ILogger logger); - private static readonly Action _writeError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.WriteError, "Flush"); + [LoggerMessage(LoggerEventIds.WriteError, LogLevel.Error, "Flush", EventName = "WriteError")] + public static partial void WriteError(ILogger logger, IOException exception); - private static readonly Action _writeErrorIgnored = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.WriteErrorIgnored, "Flush; Ignored write exception: {StatusCode}"); + [LoggerMessage(LoggerEventIds.WriteErrorIgnored, LogLevel.Debug, "Flush; Ignored write exception: {StatusCode}", EventName = "WriteFlushedIgnored")] + public static partial void WriteErrorIgnored(ILogger logger, uint statusCode); - private static readonly Action _errorWhenFlushAsync = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.ErrorWhenFlushAsync, "FlushAsync"); + [LoggerMessage(LoggerEventIds.ErrorWhenFlushAsync, LogLevel.Debug, "FlushAsync", EventName = "ErrorWhenFlushAsync")] + public static partial void ErrorWhenFlushAsync(ILogger logger, Exception exception); - private static readonly Action _writeFlushCancelled = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.WriteFlushCancelled, "FlushAsync; Write cancelled with error code: {StatusCode}"); + [LoggerMessage(LoggerEventIds.WriteFlushCancelled, LogLevel.Debug, "FlushAsync; Write cancelled with error code: {StatusCode}", EventName = "WriteFlushCancelled")] + public static partial void WriteFlushCancelled(ILogger logger, uint statusCode); - private static readonly Action _fileSendAsyncError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.FileSendAsyncError, "SendFileAsync"); + [LoggerMessage(LoggerEventIds.FileSendAsyncError, LogLevel.Error, "SendFileAsync", EventName = "FileSendAsyncError")] + public static partial void FileSendAsyncError(ILogger logger, Exception exception); - private static readonly Action _fileSendAsyncCancelled = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.FileSendAsyncCancelled, "SendFileAsync; Write cancelled with error code: {StatusCode}"); + [LoggerMessage(LoggerEventIds.FileSendAsyncCancelled, LogLevel.Debug, "SendFileAsync; Write cancelled with error code: {StatusCode}", EventName = "FileSendAsyncCancelled")] + public static partial void FileSendAsyncCancelled(ILogger logger, uint statusCode); - private static readonly Action _fileSendAsyncErrorIgnored = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.FileSendAsyncErrorIgnored, "SendFileAsync; Ignored write exception: {StatusCode}"); - - public static void FewerBytesThanExpected(ILogger logger) - { - _fewerBytesThanExpected(logger, null); - } - - public static void WriteError(ILogger logger, IOException exception) - { - _writeError(logger, exception); - } - - public static void WriteErrorIgnored(ILogger logger, uint statusCode) - { - _writeErrorIgnored(logger, statusCode, null); - } - - public static void ErrorWhenFlushAsync(ILogger logger, Exception exception) - { - _errorWhenFlushAsync(logger, exception); - } - - public static void WriteFlushCancelled(ILogger logger, uint statusCode) - { - _writeFlushCancelled(logger, statusCode, null); - } - - public static void FileSendAsyncError(ILogger logger, Exception exception) - { - _fileSendAsyncError(logger, exception); - } - - public static void FileSendAsyncCancelled(ILogger logger, uint statusCode) - { - _fileSendAsyncCancelled(logger, statusCode, null); - } - - public static void FileSendAsyncErrorIgnored(ILogger logger, uint statusCode) - { - _fileSendAsyncErrorIgnored(logger, statusCode, null); - } + [LoggerMessage(LoggerEventIds.FileSendAsyncErrorIgnored, LogLevel.Debug, "SendFileAsync; Ignored write exception: {StatusCode}", EventName = "FileSendAsyncErrorIgnored")] + public static partial void FileSendAsyncErrorIgnored(ILogger logger, uint statusCode); } } diff --git a/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.Log.cs b/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.Log.cs index b5295952bc6b..681aef3f96fa 100644 --- a/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.Log.cs +++ b/src/Servers/HttpSys/src/RequestProcessing/ResponseStreamAsyncResult.Log.cs @@ -7,30 +7,15 @@ namespace Microsoft.AspNetCore.Server.HttpSys; internal partial class ResponseStreamAsyncResult { - private static class Log + private static partial class Log { - private static readonly Action _writeCancelled = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.WriteCancelled, "FlushAsync.IOCompleted; Write cancelled with error code: {ErrorCode}"); + [LoggerMessage(LoggerEventIds.WriteCancelled, LogLevel.Debug, "FlushAsync.IOCompleted; Write cancelled with error code: {ErrorCode}", EventName = "WriteCancelled")] + public static partial void WriteCancelled(ILogger logger, uint errorCode); - private static readonly Action _writeError = - LoggerMessage.Define(LogLevel.Error, LoggerEventIds.WriteError, "FlushAsync.IOCompleted"); + [LoggerMessage(LoggerEventIds.WriteError, LogLevel.Error, "FlushAsync.IOCompleted", EventName = "WriteError")] + public static partial void WriteError(ILogger logger, Exception exception); - private static readonly Action _writeErrorIgnored = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.WriteErrorIgnored, "FlushAsync.IOCompleted; Ignored write exception: {ErrorCode}"); - - public static void WriteCancelled(ILogger logger, uint errorCode) - { - _writeCancelled(logger, errorCode, null); - } - - public static void WriteError(ILogger logger, Exception exception) - { - _writeError(logger, exception); - } - - public static void WriteErrorIgnored(ILogger logger, uint errorCode) - { - _writeErrorIgnored(logger, errorCode, null); - } + [LoggerMessage(LoggerEventIds.WriteErrorIgnored, LogLevel.Debug, "FlushAsync.IOCompleted; Ignored write exception: {ErrorCode}", EventName = "WriteErrorIgnored")] + public static partial void WriteErrorIgnored(ILogger logger, uint errorCode); } } diff --git a/src/Servers/IIS/IIS/src/Core/IISHttpContext.Log.cs b/src/Servers/IIS/IIS/src/Core/IISHttpContext.Log.cs index 1c198570fd32..2f987142ed04 100644 --- a/src/Servers/IIS/IIS/src/Core/IISHttpContext.Log.cs +++ b/src/Servers/IIS/IIS/src/Core/IISHttpContext.Log.cs @@ -8,38 +8,21 @@ namespace Microsoft.AspNetCore.Server.IIS.Core; internal abstract partial class IISHttpContext { - private static class Log + private static partial class Log { - private static readonly Action _connectionDisconnect = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "ConnectionDisconnect"), @"Connection ID ""{ConnectionId}"" disconnecting."); + [LoggerMessage(1, LogLevel.Debug, @"Connection ID ""{ConnectionId}"" disconnecting.", EventName = "ConnectionDisconnect")] + public static partial void ConnectionDisconnect(ILogger logger, string connectionId); - private static readonly Action _applicationError = - LoggerMessage.Define(LogLevel.Error, new EventId(2, "ApplicationError"), @"Connection ID ""{ConnectionId}"", Request ID ""{TraceIdentifier}"": An unhandled exception was thrown by the application."); + [LoggerMessage(2, LogLevel.Error, @"Connection ID ""{ConnectionId}"", Request ID ""{TraceIdentifier}"": An unhandled exception was thrown by the application.", EventName = "ApplicationError")] + public static partial void ApplicationError(ILogger logger, string connectionId, string traceIdentifier, Exception ex); - private static readonly Action _unexpectedError = - LoggerMessage.Define(LogLevel.Error, new EventId(3, "UnexpectedError"), @"Unexpected exception in ""{ClassName}.{MethodName}""."); - - private static readonly Action _connectionBadRequest = - LoggerMessage.Define(LogLevel.Information, new EventId(4, nameof(ConnectionBadRequest)), @"Connection id ""{ConnectionId}"" bad request data: ""{message}"""); - - public static void ConnectionDisconnect(ILogger logger, string connectionId) - { - _connectionDisconnect(logger, connectionId, null); - } - - public static void ApplicationError(ILogger logger, string connectionId, string traceIdentifier, Exception ex) - { - _applicationError(logger, connectionId, traceIdentifier, ex); - } - - public static void UnexpectedError(ILogger logger, string className, Exception ex, [CallerMemberName] string? methodName = null) - { - _unexpectedError(logger, className, methodName, ex); - } + [LoggerMessage(3, LogLevel.Error, @"Unexpected exception in ""{ClassName}.{MethodName}"".", EventName = "UnexpectedError")] + public static partial void UnexpectedError(ILogger logger, string className, Exception ex, [CallerMemberName] string? methodName = null); public static void ConnectionBadRequest(ILogger logger, string connectionId, Microsoft.AspNetCore.Http.BadHttpRequestException ex) - { - _connectionBadRequest(logger, connectionId, ex.Message, ex); - } + => ConnectionBadRequest(logger, connectionId, ex.Message, ex); + + [LoggerMessage(4, LogLevel.Information, @"Connection id ""{ConnectionId}"" bad request data: ""{message}""", EventName = nameof(ConnectionBadRequest))] + private static partial void ConnectionBadRequest(ILogger logger, string connectionId, string message, Microsoft.AspNetCore.Http.BadHttpRequestException ex); } }