diff --git a/src/Middleware/HostFiltering/src/LoggerExtensions.cs b/src/Middleware/HostFiltering/src/LoggerExtensions.cs index 847a96727fae..d00a9b53dd3b 100644 --- a/src/Middleware/HostFiltering/src/LoggerExtensions.cs +++ b/src/Middleware/HostFiltering/src/LoggerExtensions.cs @@ -1,42 +1,31 @@ // 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 Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.HostFiltering { - internal static class LoggerExtensions + internal static partial class LoggerExtensions { - private static readonly LogDefineOptions SkipEnabledCheckLogOptions = new() { SkipEnabledCheck = true }; + [LoggerMessage(0, LogLevel.Debug, "Wildcard detected, all requests with hosts will be allowed.", EventName = "WildcardDetected")] + public static partial void WildcardDetected(this ILogger logger); - private static readonly Action _wildcardDetected = - LoggerMessage.Define(LogLevel.Debug, new EventId(0, "WildcardDetected"), "Wildcard detected, all requests with hosts will be allowed."); + [LoggerMessage(1, LogLevel.Debug, "Allowed hosts: {Hosts}", EventName = "AllowedHosts", SkipEnabledCheck = true)] + public static partial void AllowedHosts(this ILogger logger, string hosts); - private static readonly Action _allowedHosts = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "AllowedHosts"), "Allowed hosts: {Hosts}", SkipEnabledCheckLogOptions); + [LoggerMessage(2, LogLevel.Trace, "All hosts are allowed.", EventName = "AllHostsAllowed")] + public static partial void AllHostsAllowed(this ILogger logger); - private static readonly Action _allHostsAllowed = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "AllHostsAllowed"), "All hosts are allowed."); + [LoggerMessage(3, LogLevel.Information, "{Protocol} request rejected due to missing or empty host header.", EventName = "RequestRejectedMissingHost")] + public static partial void RequestRejectedMissingHost(this ILogger logger, string protocol); - private static readonly Action _requestRejectedMissingHost = - LoggerMessage.Define(LogLevel.Information, new EventId(3, "RequestRejectedMissingHost"), "{Protocol} request rejected due to missing or empty host header."); + [LoggerMessage(4, LogLevel.Debug, "{Protocol} request allowed with missing or empty host header.", EventName = "RequestAllowedMissingHost")] + public static partial void RequestAllowedMissingHost(this ILogger logger, string protocol); - private static readonly Action _requestAllowedMissingHost = - LoggerMessage.Define(LogLevel.Debug, new EventId(4, "RequestAllowedMissingHost"), "{Protocol} request allowed with missing or empty host header."); + [LoggerMessage(5, LogLevel.Trace, "The host '{Host}' matches an allowed host.", EventName = "AllowedHostMatched")] + public static partial void AllowedHostMatched(this ILogger logger, string host); - private static readonly Action _allowedHostMatched = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "AllowedHostMatched"), "The host '{Host}' matches an allowed host."); - - private static readonly Action _noAllowedHostMatched = - LoggerMessage.Define(LogLevel.Information, new EventId(6, "NoAllowedHostMatched"), "The host '{Host}' does not match an allowed host."); - - public static void WildcardDetected(this ILogger logger) => _wildcardDetected(logger, null); - public static void AllowedHosts(this ILogger logger, string allowedHosts) => _allowedHosts(logger, allowedHosts, null); - public static void AllHostsAllowed(this ILogger logger) => _allHostsAllowed(logger, null); - public static void RequestRejectedMissingHost(this ILogger logger, string protocol) => _requestRejectedMissingHost(logger, protocol, null); - public static void RequestAllowedMissingHost(this ILogger logger, string protocol) => _requestAllowedMissingHost(logger, protocol, null); - public static void AllowedHostMatched(this ILogger logger, string host) => _allowedHostMatched(logger, host, null); - public static void NoAllowedHostMatched(this ILogger logger, string host) => _noAllowedHostMatched(logger, host, null); + [LoggerMessage(6, LogLevel.Information, "The host '{Host}' does not match an allowed host.", EventName = "NoAllowedHostMatched")] + public static partial void NoAllowedHostMatched(this ILogger logger, string host); } } diff --git a/src/Middleware/HttpsPolicy/src/HstsLoggingExtensions.cs b/src/Middleware/HttpsPolicy/src/HstsLoggingExtensions.cs index f673b30784cb..b6f4c43d959a 100644 --- a/src/Middleware/HttpsPolicy/src/HstsLoggingExtensions.cs +++ b/src/Middleware/HttpsPolicy/src/HstsLoggingExtensions.cs @@ -6,43 +6,15 @@ namespace Microsoft.AspNetCore.HttpsPolicy { - internal static class HstsLoggingExtensions + internal static partial class HstsLoggingExtensions { - private static readonly Action _notSecure; - private static readonly Action _excludedHost; - private static readonly Action _addingHstsHeader; + [LoggerMessage(1, LogLevel.Debug, "The request is insecure. Skipping HSTS header.", EventName = "NotSecure")] + public static partial void SkippingInsecure(this ILogger logger); - static HstsLoggingExtensions() - { - _notSecure = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "NotSecure"), - "The request is insecure. Skipping HSTS header."); + [LoggerMessage(2, LogLevel.Debug, "The host '{host}' is excluded. Skipping HSTS header.", EventName = "ExcludedHost")] + public static partial void SkippingExcludedHost(this ILogger logger, string host); - _excludedHost = LoggerMessage.Define( - LogLevel.Debug, - new EventId(2, "ExcludedHost"), - "The host '{host}' is excluded. Skipping HSTS header."); - - _addingHstsHeader = LoggerMessage.Define( - LogLevel.Trace, - new EventId(3, "AddingHstsHeader"), - "Adding HSTS header to response."); - } - - public static void SkippingInsecure(this ILogger logger) - { - _notSecure(logger, null); - } - - public static void SkippingExcludedHost(this ILogger logger, string host) - { - _excludedHost(logger, host, null); - } - - public static void AddingHstsHeader(this ILogger logger) - { - _addingHstsHeader(logger, null); - } + [LoggerMessage(3, LogLevel.Trace, "Adding HSTS header to response.", EventName = "AddingHstsHeader")] + public static partial void AddingHstsHeader(this ILogger logger); } } diff --git a/src/Middleware/HttpsPolicy/src/HttpsLoggingExtensions.cs b/src/Middleware/HttpsPolicy/src/HttpsLoggingExtensions.cs index 244ec1f07078..9d511cbb6c07 100644 --- a/src/Middleware/HttpsPolicy/src/HttpsLoggingExtensions.cs +++ b/src/Middleware/HttpsPolicy/src/HttpsLoggingExtensions.cs @@ -6,54 +6,18 @@ namespace Microsoft.AspNetCore.HttpsPolicy { - internal static class HttpsLoggingExtensions + internal static partial class HttpsLoggingExtensions { - private static readonly Action _redirectingToHttps; - private static readonly Action _portLoadedFromConfig; - private static readonly Action _failedToDeterminePort; - private static readonly Action _portFromServer; + [LoggerMessage(1, LogLevel.Debug, "Redirecting to '{redirect}'.", EventName = "RedirectingToHttps")] + public static partial void RedirectingToHttps(this ILogger logger, string redirect); - static HttpsLoggingExtensions() - { - _redirectingToHttps = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "RedirectingToHttps"), - "Redirecting to '{redirect}'."); + [LoggerMessage(2, LogLevel.Debug, "Https port '{port}' loaded from configuration.", EventName = "PortLoadedFromConfig")] + public static partial void PortLoadedFromConfig(this ILogger logger, int port); - _portLoadedFromConfig = LoggerMessage.Define( - LogLevel.Debug, - new EventId(2, "PortLoadedFromConfig"), - "Https port '{port}' loaded from configuration."); + [LoggerMessage(3, LogLevel.Warning, "Failed to determine the https port for redirect.", EventName = "FailedToDeterminePort")] + public static partial void FailedToDeterminePort(this ILogger logger); - _failedToDeterminePort = LoggerMessage.Define( - LogLevel.Warning, - new EventId(3, "FailedToDeterminePort"), - "Failed to determine the https port for redirect."); - - _portFromServer = LoggerMessage.Define( - LogLevel.Debug, - new EventId(5, "PortFromServer"), - "Https port '{httpsPort}' discovered from server endpoints."); - } - - public static void RedirectingToHttps(this ILogger logger, string redirect) - { - _redirectingToHttps(logger, redirect, null); - } - - public static void PortLoadedFromConfig(this ILogger logger, int port) - { - _portLoadedFromConfig(logger, port, null); - } - - public static void FailedToDeterminePort(this ILogger logger) - { - _failedToDeterminePort(logger, null); - } - - public static void PortFromServer(this ILogger logger, int port) - { - _portFromServer(logger, port, null); - } + [LoggerMessage(5, LogLevel.Debug, "Https port '{httpsPort}' discovered from server endpoints.", EventName = "PortFromServer")] + public static partial void PortFromServer(this ILogger logger, int httpsPort); } } diff --git a/src/Middleware/Localization/src/RequestCultureProviderLoggerExtensions.cs b/src/Middleware/Localization/src/RequestCultureProviderLoggerExtensions.cs index d6ada0b42cf1..497db2afbe58 100644 --- a/src/Middleware/Localization/src/RequestCultureProviderLoggerExtensions.cs +++ b/src/Middleware/Localization/src/RequestCultureProviderLoggerExtensions.cs @@ -8,31 +8,13 @@ namespace Microsoft.AspNetCore.Localization { - internal static class RequestCultureProviderLoggerExtensions + internal static partial class RequestCultureProviderLoggerExtensions { - private static readonly Action, Exception?> _unsupportedCulture; - private static readonly Action, Exception?> _unsupportedUICulture; - static RequestCultureProviderLoggerExtensions() - { - _unsupportedCulture = LoggerMessage.Define>( - LogLevel.Debug, - new EventId (1, "UnsupportedCulture"), - "{requestCultureProvider} returned the following unsupported cultures '{cultures}'."); - _unsupportedUICulture = LoggerMessage.Define>( - LogLevel.Debug, - new EventId(2, "UnsupportedUICulture"), - "{requestCultureProvider} returned the following unsupported UI Cultures '{uiCultures}'."); - } + [LoggerMessage(1, LogLevel.Debug, "{requestCultureProvider} returned the following unsupported cultures '{cultures}'.", EventName = "UnsupportedCulture")] + public static partial void UnsupportedCultures(this ILogger logger, string requestCultureProvider, IList cultures); - public static void UnsupportedCultures(this ILogger logger, string requestCultureProvider, IList cultures) - { - _unsupportedCulture(logger, requestCultureProvider, cultures, null); - } - - public static void UnsupportedUICultures(this ILogger logger, string requestCultureProvider, IList uiCultures) - { - _unsupportedUICulture(logger, requestCultureProvider, uiCultures, null); - } + [LoggerMessage(2, LogLevel.Debug, "{requestCultureProvider} returned the following unsupported UI Cultures '{uiCultures}'.", EventName = "UnsupportedUICulture")] + public static partial void UnsupportedUICultures(this ILogger logger, string requestCultureProvider, IList uiCultures); } } diff --git a/src/Middleware/ResponseCaching/src/LoggerExtensions.cs b/src/Middleware/ResponseCaching/src/LoggerExtensions.cs index f8c54ba8e323..99949e70fdf0 100644 --- a/src/Middleware/ResponseCaching/src/LoggerExtensions.cs +++ b/src/Middleware/ResponseCaching/src/LoggerExtensions.cs @@ -10,301 +10,116 @@ namespace Microsoft.AspNetCore.ResponseCaching /// /// Defines *all* the logger messages produced by response caching /// - internal static class LoggerExtensions + internal static partial class LoggerExtensions { - private static readonly Action _requestMethodNotCacheable; - private static readonly Action _requestWithAuthorizationNotCacheable; - private static readonly Action _requestWithNoCacheNotCacheable; - private static readonly Action _requestWithPragmaNoCacheNotCacheable; - private static readonly Action _expirationMinFreshAdded; - private static readonly Action _expirationSharedMaxAgeExceeded; - private static readonly Action _expirationMustRevalidate; - private static readonly Action _expirationMaxStaleSatisfied; - private static readonly Action _expirationMaxAgeExceeded; - private static readonly Action _expirationExpiresExceeded; - private static readonly Action _responseWithoutPublicNotCacheable; - private static readonly Action _responseWithNoStoreNotCacheable; - private static readonly Action _responseWithNoCacheNotCacheable; - private static readonly Action _responseWithSetCookieNotCacheable; - private static readonly Action _responseWithVaryStarNotCacheable; - private static readonly Action _responseWithPrivateNotCacheable; - private static readonly Action _responseWithUnsuccessfulStatusCodeNotCacheable; - private static readonly Action _notModifiedIfNoneMatchStar; - private static readonly Action _notModifiedIfNoneMatchMatched; - private static readonly Action _notModifiedIfModifiedSinceSatisfied; - private static readonly Action _notModifiedServed; - private static readonly Action _cachedResponseServed; - private static readonly Action _gatewayTimeoutServed; - private static readonly Action _noResponseServed; - private static readonly Action _varyByRulesUpdated; - private static readonly Action _responseCached; - private static readonly Action _responseNotCached; - private static readonly Action _responseContentLengthMismatchNotCached; - private static readonly Action _expirationInfiniteMaxStaleSatisfied; + [LoggerMessage(1, LogLevel.Debug, "The request cannot be served from cache because it uses the HTTP method: {Method}.", + EventName = "RequestMethodNotCacheable")] + internal static partial void RequestMethodNotCacheable(this ILogger logger, string method); - static LoggerExtensions() - { - _requestMethodNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(1, "RequestMethodNotCacheable"), - formatString: "The request cannot be served from cache because it uses the HTTP method: {Method}."); - _requestWithAuthorizationNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(2, "RequestWithAuthorizationNotCacheable"), - formatString: $"The request cannot be served from cache because it contains an '{HeaderNames.Authorization}' header."); - _requestWithNoCacheNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(3, "RequestWithNoCacheNotCacheable"), - formatString: "The request cannot be served from cache because it contains a 'no-cache' cache directive."); - _requestWithPragmaNoCacheNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(4, "RequestWithPragmaNoCacheNotCacheable"), - formatString: "The request cannot be served from cache because it contains a 'no-cache' pragma directive."); - _expirationMinFreshAdded = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(5, "LogRequestMethodNotCacheable"), - formatString: "Adding a minimum freshness requirement of {Duration} specified by the 'min-fresh' cache directive."); - _expirationSharedMaxAgeExceeded = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(6, "ExpirationSharedMaxAgeExceeded"), - formatString: "The age of the entry is {Age} and has exceeded the maximum age for shared caches of {SharedMaxAge} specified by the 's-maxage' cache directive."); - _expirationMustRevalidate = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(7, "ExpirationMustRevalidate"), - formatString: "The age of the entry is {Age} and has exceeded the maximum age of {MaxAge} specified by the 'max-age' cache directive. It must be revalidated because the 'must-revalidate' or 'proxy-revalidate' cache directive is specified."); - _expirationMaxStaleSatisfied = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(8, "ExpirationMaxStaleSatisfied"), - formatString: "The age of the entry is {Age} and has exceeded the maximum age of {MaxAge} specified by the 'max-age' cache directive. However, it satisfied the maximum stale allowance of {MaxStale} specified by the 'max-stale' cache directive."); - _expirationMaxAgeExceeded = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(9, "ExpirationMaxAgeExceeded"), - formatString: "The age of the entry is {Age} and has exceeded the maximum age of {MaxAge} specified by the 'max-age' cache directive."); - _expirationExpiresExceeded = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(10, "ExpirationExpiresExceeded"), - formatString: $"The response time of the entry is {{ResponseTime}} and has exceeded the expiry date of {{Expired}} specified by the '{HeaderNames.Expires}' header."); - _responseWithoutPublicNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(11, "ResponseWithoutPublicNotCacheable"), - formatString: "Response is not cacheable because it does not contain the 'public' cache directive."); - _responseWithNoStoreNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(12, "ResponseWithNoStoreNotCacheable"), - formatString: "Response is not cacheable because it or its corresponding request contains a 'no-store' cache directive."); - _responseWithNoCacheNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(13, "ResponseWithNoCacheNotCacheable"), - formatString: "Response is not cacheable because it contains a 'no-cache' cache directive."); - _responseWithSetCookieNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(14, "ResponseWithSetCookieNotCacheable"), - formatString: $"Response is not cacheable because it contains a '{HeaderNames.SetCookie}' header."); - _responseWithVaryStarNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(15, "ResponseWithVaryStarNotCacheable"), - formatString: $"Response is not cacheable because it contains a '{HeaderNames.Vary}' header with a value of *."); - _responseWithPrivateNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(16, "ResponseWithPrivateNotCacheable"), - formatString: "Response is not cacheable because it contains the 'private' cache directive."); - _responseWithUnsuccessfulStatusCodeNotCacheable = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(17, "ResponseWithUnsuccessfulStatusCodeNotCacheable"), - formatString: "Response is not cacheable because its status code {StatusCode} does not indicate success."); - _notModifiedIfNoneMatchStar = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(18, "ExpirationExpiresExceeded"), - formatString: $"The '{HeaderNames.IfNoneMatch}' header of the request contains a value of *."); - _notModifiedIfNoneMatchMatched = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(19, "NotModifiedIfNoneMatchMatched"), - formatString: $"The ETag {{ETag}} in the '{HeaderNames.IfNoneMatch}' header matched the ETag of a cached entry."); - _notModifiedIfModifiedSinceSatisfied = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(20, "NotModifiedIfModifiedSinceSatisfied"), - formatString: $"The last modified date of {{LastModified}} is before the date {{IfModifiedSince}} specified in the '{HeaderNames.IfModifiedSince}' header."); - _notModifiedServed = LoggerMessage.Define( - logLevel: LogLevel.Information, - eventId: new EventId(21, "NotModifiedServed"), - formatString: "The content requested has not been modified."); - _cachedResponseServed = LoggerMessage.Define( - logLevel: LogLevel.Information, - eventId: new EventId(22, "CachedResponseServed"), - formatString: "Serving response from cache."); - _gatewayTimeoutServed = LoggerMessage.Define( - logLevel: LogLevel.Information, - eventId: new EventId(23, "GatewayTimeoutServed"), - formatString: "No cached response available for this request and the 'only-if-cached' cache directive was specified."); - _noResponseServed = LoggerMessage.Define( - logLevel: LogLevel.Information, - eventId: new EventId(24, "NoResponseServed"), - formatString: "No cached response available for this request."); - _varyByRulesUpdated = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(25, "VaryByRulesUpdated"), - formatString: "Vary by rules were updated. Headers: {Headers}, Query keys: {QueryKeys}"); - _responseCached = LoggerMessage.Define( - logLevel: LogLevel.Information, - eventId: new EventId(26, "ResponseCached"), - formatString: "The response has been cached."); - _responseNotCached = LoggerMessage.Define( - logLevel: LogLevel.Information, - eventId: new EventId(27, "ResponseNotCached"), - formatString: "The response could not be cached for this request."); - _responseContentLengthMismatchNotCached = LoggerMessage.Define( - logLevel: LogLevel.Warning, - eventId: new EventId(28, "responseContentLengthMismatchNotCached"), - formatString: $"The response could not be cached for this request because the '{HeaderNames.ContentLength}' did not match the body length."); - _expirationInfiniteMaxStaleSatisfied = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(29, "ExpirationInfiniteMaxStaleSatisfied"), - formatString: "The age of the entry is {Age} and has exceeded the maximum age of {MaxAge} specified by the 'max-age' cache directive. However, the 'max-stale' cache directive was specified without an assigned value and a stale response of any age is accepted."); - } + [LoggerMessage(2, LogLevel.Debug, "The request cannot be served from cache because it contains an 'Authorization' header.", + EventName = "RequestWithAuthorizationNotCacheable")] + internal static partial void RequestWithAuthorizationNotCacheable(this ILogger logger); - internal static void RequestMethodNotCacheable(this ILogger logger, string method) - { - _requestMethodNotCacheable(logger, method, null); - } + [LoggerMessage(3, LogLevel.Debug, "The request cannot be served from cache because it contains a 'no-cache' cache directive.", + EventName = "RequestWithNoCacheNotCacheable")] + internal static partial void RequestWithNoCacheNotCacheable(this ILogger logger); - internal static void RequestWithAuthorizationNotCacheable(this ILogger logger) - { - _requestWithAuthorizationNotCacheable(logger, null); - } + [LoggerMessage(4, LogLevel.Debug, "The request cannot be served from cache because it contains a 'no-cache' pragma directive.", + EventName = "RequestWithPragmaNoCacheNotCacheable")] + internal static partial void RequestWithPragmaNoCacheNotCacheable(this ILogger logger); - internal static void RequestWithNoCacheNotCacheable(this ILogger logger) - { - _requestWithNoCacheNotCacheable(logger, null); - } + [LoggerMessage(5, LogLevel.Debug, "Adding a minimum freshness requirement of {Duration} specified by the 'min-fresh' cache directive.", + EventName = "LogRequestMethodNotCacheable")] + internal static partial void ExpirationMinFreshAdded(this ILogger logger, TimeSpan duration); - internal static void RequestWithPragmaNoCacheNotCacheable(this ILogger logger) - { - _requestWithPragmaNoCacheNotCacheable(logger, null); - } + [LoggerMessage(6, LogLevel.Debug, "The age of the entry is {Age} and has exceeded the maximum age for shared caches of {SharedMaxAge} specified by the 's-maxage' cache directive.", + EventName = "ExpirationSharedMaxAgeExceeded")] + internal static partial void ExpirationSharedMaxAgeExceeded(this ILogger logger, TimeSpan age, TimeSpan sharedMaxAge); - internal static void ExpirationMinFreshAdded(this ILogger logger, TimeSpan duration) - { - _expirationMinFreshAdded(logger, duration, null); - } + [LoggerMessage(7, LogLevel.Debug, "The age of the entry is {Age} and has exceeded the maximum age of {MaxAge} specified by the 'max-age' cache directive. " + + "It must be revalidated because the 'must-revalidate' or 'proxy-revalidate' cache directive is specified.", + EventName = "ExpirationMustRevalidate")] + internal static partial void ExpirationMustRevalidate(this ILogger logger, TimeSpan age, TimeSpan maxAge); - internal static void ExpirationSharedMaxAgeExceeded(this ILogger logger, TimeSpan age, TimeSpan sharedMaxAge) - { - _expirationSharedMaxAgeExceeded(logger, age, sharedMaxAge, null); - } + [LoggerMessage(8, LogLevel.Debug, "The age of the entry is {Age} and has exceeded the maximum age of {MaxAge} specified by the 'max-age' cache directive. " + + "However, it satisfied the maximum stale allowance of {MaxStale} specified by the 'max-stale' cache directive.", + EventName = "ExpirationMaxStaleSatisfied")] + internal static partial void ExpirationMaxStaleSatisfied(this ILogger logger, TimeSpan age, TimeSpan maxAge, TimeSpan maxStale); - internal static void ExpirationMustRevalidate(this ILogger logger, TimeSpan age, TimeSpan maxAge) - { - _expirationMustRevalidate(logger, age, maxAge, null); - } + [LoggerMessage(9, LogLevel.Debug, "The age of the entry is {Age} and has exceeded the maximum age of {MaxAge} specified by the 'max-age' cache directive.", EventName = "ExpirationMaxAgeExceeded")] + internal static partial void ExpirationMaxAgeExceeded(this ILogger logger, TimeSpan age, TimeSpan maxAge); - internal static void ExpirationMaxStaleSatisfied(this ILogger logger, TimeSpan age, TimeSpan maxAge, TimeSpan maxStale) - { - _expirationMaxStaleSatisfied(logger, age, maxAge, maxStale, null); - } + [LoggerMessage(10, LogLevel.Debug, "The response time of the entry is {ResponseTime} and has exceeded the expiry date of {Expired} specified by the 'Expires' header.", + EventName = "ExpirationExpiresExceeded")] + internal static partial void ExpirationExpiresExceeded(this ILogger logger, DateTimeOffset responseTime, DateTimeOffset expired); - internal static void ExpirationMaxAgeExceeded(this ILogger logger, TimeSpan age, TimeSpan sharedMaxAge) - { - _expirationMaxAgeExceeded(logger, age, sharedMaxAge, null); - } + [LoggerMessage(11, LogLevel.Debug, "Response is not cacheable because it does not contain the 'public' cache directive.", + EventName = "ResponseWithoutPublicNotCacheable")] + internal static partial void ResponseWithoutPublicNotCacheable(this ILogger logger); - internal static void ExpirationExpiresExceeded(this ILogger logger, DateTimeOffset responseTime, DateTimeOffset expires) - { - _expirationExpiresExceeded(logger, responseTime, expires, null); - } + [LoggerMessage(12, LogLevel.Debug, "Response is not cacheable because it or its corresponding request contains a 'no-store' cache directive.", + EventName = "ResponseWithNoStoreNotCacheable")] + internal static partial void ResponseWithNoStoreNotCacheable(this ILogger logger); + [LoggerMessage(13, LogLevel.Debug, "Response is not cacheable because it contains a 'no-cache' cache directive.", + EventName = "ResponseWithNoCacheNotCacheable")] + internal static partial void ResponseWithNoCacheNotCacheable(this ILogger logger); - internal static void ResponseWithoutPublicNotCacheable(this ILogger logger) - { - _responseWithoutPublicNotCacheable(logger, null); - } + [LoggerMessage(14, LogLevel.Debug, "Response is not cacheable because it contains a 'SetCookie' header.", EventName = "ResponseWithSetCookieNotCacheable")] + internal static partial void ResponseWithSetCookieNotCacheable(this ILogger logger); - internal static void ResponseWithNoStoreNotCacheable(this ILogger logger) - { - _responseWithNoStoreNotCacheable(logger, null); - } + [LoggerMessage(15, LogLevel.Debug, "Response is not cacheable because it contains a '.Vary' header with a value of *.", + EventName = "ResponseWithVaryStarNotCacheable")] + internal static partial void ResponseWithVaryStarNotCacheable(this ILogger logger); - internal static void ResponseWithNoCacheNotCacheable(this ILogger logger) - { - _responseWithNoCacheNotCacheable(logger, null); - } + [LoggerMessage(16, LogLevel.Debug, "Response is not cacheable because it contains the 'private' cache directive.", + EventName = "ResponseWithPrivateNotCacheable")] + internal static partial void ResponseWithPrivateNotCacheable(this ILogger logger); - internal static void ResponseWithSetCookieNotCacheable(this ILogger logger) - { - _responseWithSetCookieNotCacheable(logger, null); - } + [LoggerMessage(17, LogLevel.Debug, "Response is not cacheable because its status code {StatusCode} does not indicate success.", + EventName = "ResponseWithUnsuccessfulStatusCodeNotCacheable")] + internal static partial void ResponseWithUnsuccessfulStatusCodeNotCacheable(this ILogger logger, int statusCode); - internal static void ResponseWithVaryStarNotCacheable(this ILogger logger) - { - _responseWithVaryStarNotCacheable(logger, null); - } + [LoggerMessage(18, LogLevel.Debug, "The 'IfNoneMatch' header of the request contains a value of *.", EventName = "ExpirationExpiresExceeded")] + internal static partial void NotModifiedIfNoneMatchStar(this ILogger logger); - internal static void ResponseWithPrivateNotCacheable(this ILogger logger) - { - _responseWithPrivateNotCacheable(logger, null); - } + [LoggerMessage(19, LogLevel.Debug, "The ETag {ETag} in the 'IfNoneMatch' header matched the ETag of a cached entry.", + EventName = "NotModifiedIfNoneMatchMatched")] + internal static partial void NotModifiedIfNoneMatchMatched(this ILogger logger, EntityTagHeaderValue etag); - internal static void ResponseWithUnsuccessfulStatusCodeNotCacheable(this ILogger logger, int statusCode) - { - _responseWithUnsuccessfulStatusCodeNotCacheable(logger, statusCode, null); - } + [LoggerMessage(20, LogLevel.Debug, "The last modified date of {LastModified} is before the date {IfModifiedSince} specified in the 'IfModifiedSince' header.", + EventName = "NotModifiedIfModifiedSinceSatisfied")] + internal static partial void NotModifiedIfModifiedSinceSatisfied(this ILogger logger, DateTimeOffset lastModified, DateTimeOffset ifModifiedSince); - internal static void NotModifiedIfNoneMatchStar(this ILogger logger) - { - _notModifiedIfNoneMatchStar(logger, null); - } + [LoggerMessage(21, LogLevel.Information, "The content requested has not been modified.", EventName = "NotModifiedServed")] + internal static partial void NotModifiedServed(this ILogger logger); - internal static void NotModifiedIfNoneMatchMatched(this ILogger logger, EntityTagHeaderValue etag) - { - _notModifiedIfNoneMatchMatched(logger, etag, null); - } + [LoggerMessage(22, LogLevel.Information, "Serving response from cache.", EventName = "CachedResponseServed")] + internal static partial void CachedResponseServed(this ILogger logger); - internal static void NotModifiedIfModifiedSinceSatisfied(this ILogger logger, DateTimeOffset lastModified, DateTimeOffset ifModifiedSince) - { - _notModifiedIfModifiedSinceSatisfied(logger, lastModified, ifModifiedSince, null); - } + [LoggerMessage(23, LogLevel.Information, "No cached response available for this request and the 'only-if-cached' cache directive was specified.", + EventName = "GatewayTimeoutServed")] + internal static partial void GatewayTimeoutServed(this ILogger logger); - internal static void NotModifiedServed(this ILogger logger) - { - _notModifiedServed(logger, null); - } + [LoggerMessage(24, LogLevel.Information, "No cached response available for this request.", EventName = "NoResponseServed")] + internal static partial void NoResponseServed(this ILogger logger); - internal static void CachedResponseServed(this ILogger logger) - { - _cachedResponseServed(logger, null); - } + [LoggerMessage(25, LogLevel.Debug, "Vary by rules were updated. Headers: {Headers}, Query keys: {QueryKeys}", EventName = "VaryByRulesUpdated")] + internal static partial void VaryByRulesUpdated(this ILogger logger, string headers, string queryKeys); - internal static void GatewayTimeoutServed(this ILogger logger) - { - _gatewayTimeoutServed(logger, null); - } + [LoggerMessage(26, LogLevel.Information, "The response has been cached.", EventName = "ResponseCached")] + internal static partial void ResponseCached(this ILogger logger); - internal static void NoResponseServed(this ILogger logger) - { - _noResponseServed(logger, null); - } + [LoggerMessage(27, LogLevel.Information, "The response could not be cached for this request.", EventName = "ResponseNotCached")] + internal static partial void LogResponseNotCached(this ILogger logger); - internal static void VaryByRulesUpdated(this ILogger logger, string headers, string queryKeys) - { - _varyByRulesUpdated(logger, headers, queryKeys, null); - } + [LoggerMessage(28, LogLevel.Warning, "The response could not be cached for this request because the 'Content-Length' did not match the body length.", + EventName = "responseContentLengthMismatchNotCached")] + internal static partial void ResponseContentLengthMismatchNotCached(this ILogger logger); - internal static void ResponseCached(this ILogger logger) - { - _responseCached(logger, null); - } - - internal static void LogResponseNotCached(this ILogger logger) - { - _responseNotCached(logger, null); - } - - internal static void ResponseContentLengthMismatchNotCached(this ILogger logger) - { - _responseContentLengthMismatchNotCached(logger, null); - } - - internal static void ExpirationInfiniteMaxStaleSatisfied(this ILogger logger, TimeSpan age, TimeSpan maxAge) - { - _expirationInfiniteMaxStaleSatisfied(logger, age, maxAge, null); - } + [LoggerMessage(29, LogLevel.Debug, + "The age of the entry is {Age} and has exceeded the maximum age of {MaxAge} specified by the 'max-age' cache directive. " + + "However, the 'max-stale' cache directive was specified without an assigned value and a stale response of any age is accepted.", + EventName = "ExpirationInfiniteMaxStaleSatisfied")] + internal static partial void ExpirationInfiniteMaxStaleSatisfied(this ILogger logger, TimeSpan age, TimeSpan maxAge); } } diff --git a/src/Middleware/ResponseCompression/src/ResponseCompressionLoggingExtensions.cs b/src/Middleware/ResponseCompression/src/ResponseCompressionLoggingExtensions.cs index cdc9427f5721..8c43aa1e66ac 100644 --- a/src/Middleware/ResponseCompression/src/ResponseCompressionLoggingExtensions.cs +++ b/src/Middleware/ResponseCompression/src/ResponseCompressionLoggingExtensions.cs @@ -6,98 +6,30 @@ namespace Microsoft.AspNetCore.ResponseCompression { - internal static class ResponseCompressionLoggingExtensions + internal static partial class ResponseCompressionLoggingExtensions { - private static readonly Action _noAcceptEncoding; - private static readonly Action _noCompressionForHttps; - private static readonly Action _requestAcceptsCompression; - private static readonly Action _noCompressionDueToHeader; - private static readonly Action _noCompressionForContentType; - private static readonly Action _shouldCompressResponse; - private static readonly Action _noCompressionProvider; - private static readonly Action _compressWith; + [LoggerMessage(1, LogLevel.Debug, "No response compression available, the Accept-Encoding header is missing or invalid.", EventName = "NoAcceptEncoding")] + public static partial void NoAcceptEncoding(this ILogger logger); - static ResponseCompressionLoggingExtensions() - { - _noAcceptEncoding = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "NoAcceptEncoding"), - "No response compression available, the Accept-Encoding header is missing or invalid."); + [LoggerMessage(2, LogLevel.Debug, "No response compression available for HTTPS requests. See ResponseCompressionOptions.EnableForHttps.", EventName = "NoCompressionForHttps")] + public static partial void NoCompressionForHttps(this ILogger logger); - _noCompressionForHttps = LoggerMessage.Define( - LogLevel.Debug, - new EventId(2, "NoCompressionForHttps"), - "No response compression available for HTTPS requests. See ResponseCompressionOptions.EnableForHttps."); + [LoggerMessage(3, LogLevel.Trace, "This request accepts compression.", EventName = "RequestAcceptsCompression")] + public static partial void RequestAcceptsCompression(this ILogger logger); - _requestAcceptsCompression = LoggerMessage.Define( - LogLevel.Trace, - new EventId(3, "RequestAcceptsCompression"), - "This request accepts compression."); + [LoggerMessage(4, LogLevel.Debug, "Response compression disabled due to the {header} header.", EventName = "NoCompressionDueToHeader")] + public static partial void NoCompressionDueToHeader(this ILogger logger, string header); - _noCompressionDueToHeader = LoggerMessage.Define( - LogLevel.Debug, - new EventId(4, "NoCompressionDueToHeader"), - "Response compression disabled due to the {header} header."); + [LoggerMessage(5, LogLevel.Debug, "Response compression is not enabled for the Content-Type '{header}'.", EventName = "NoCompressionForContentType")] + public static partial void NoCompressionForContentType(this ILogger logger, string header); - _noCompressionForContentType = LoggerMessage.Define( - LogLevel.Debug, - new EventId(5, "NoCompressionForContentType"), - "Response compression is not enabled for the Content-Type '{header}'."); + [LoggerMessage(6, LogLevel.Trace, "Response compression is available for this Content-Type.", EventName = "ShouldCompressResponse")] + public static partial void ShouldCompressResponse(this ILogger logger); - _shouldCompressResponse = LoggerMessage.Define( - LogLevel.Trace, - new EventId(6, "ShouldCompressResponse"), - "Response compression is available for this Content-Type."); + [LoggerMessage(7, LogLevel.Debug, "No matching response compression provider found.", EventName = "NoCompressionProvider")] + public static partial void NoCompressionProvider(this ILogger logger); - _noCompressionProvider = LoggerMessage.Define( - LogLevel.Debug, - new EventId(7, "NoCompressionProvider"), - "No matching response compression provider found."); - - _compressWith = LoggerMessage.Define( - LogLevel.Debug, - new EventId(8, "CompressWith"), - "The response will be compressed with '{provider}'."); - } - - public static void NoAcceptEncoding(this ILogger logger) - { - _noAcceptEncoding(logger, null); - } - - public static void NoCompressionForHttps(this ILogger logger) - { - _noCompressionForHttps(logger, null); - } - - public static void RequestAcceptsCompression(this ILogger logger) - { - _requestAcceptsCompression(logger, null); - } - - public static void NoCompressionDueToHeader(this ILogger logger, string header) - { - _noCompressionDueToHeader(logger, header, null); - } - - public static void NoCompressionForContentType(this ILogger logger, string header) - { - _noCompressionForContentType(logger, header, null); - } - - public static void ShouldCompressResponse(this ILogger logger) - { - _shouldCompressResponse(logger, null); - } - - public static void NoCompressionProvider(this ILogger logger) - { - _noCompressionProvider(logger, null); - } - - public static void CompressingWith(this ILogger logger, string provider) - { - _compressWith(logger, provider, null); - } + [LoggerMessage(8, LogLevel.Debug, "The response will be compressed with '{provider}'.", EventName = "CompressWith")] + public static partial void CompressingWith(this ILogger logger, string provider); } } diff --git a/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs b/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs index 50c040ca5dbc..92e7b1887a97 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters /// /// A for JSON content that uses . /// - public class SystemTextJsonInputFormatter : TextInputFormatter, IInputFormatterExceptionPolicy + public partial class SystemTextJsonInputFormatter : TextInputFormatter, IInputFormatterExceptionPolicy { private readonly JsonOptions _jsonOptions; private readonly ILogger _logger; @@ -144,28 +144,19 @@ private Exception WrapExceptionForModelState(JsonException jsonException) return (inputStream, true); } - private static class Log + private static partial class Log { - private static readonly Action _jsonInputFormatterException; - private static readonly Action _jsonInputSuccess; - - static Log() - { - _jsonInputFormatterException = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "SystemTextJsonInputException"), - "JSON input formatter threw an exception: {Message}"); - _jsonInputSuccess = LoggerMessage.Define( - LogLevel.Debug, - new EventId(2, "SystemTextJsonInputSuccess"), - "JSON input formatter succeeded, deserializing to type '{TypeName}'"); - } + [LoggerMessage(1, LogLevel.Debug, "JSON input formatter threw an exception: {Message}", EventName = "SystemTextJsonInputException")] + private static partial void JsonInputException(ILogger logger, string message); public static void JsonInputException(ILogger logger, Exception exception) - => _jsonInputFormatterException(logger, exception.Message, exception); + => JsonInputException(logger, exception.Message); + + [LoggerMessage(2, LogLevel.Debug, "JSON input formatter succeeded, deserializing to type '{TypeName}'", EventName = "SystemTextJsonInputSuccess")] + private static partial void JsonInputSuccess(ILogger logger, string? typeName); public static void JsonInputSuccess(ILogger logger, Type modelType) - => _jsonInputSuccess(logger, modelType.FullName, null); + => JsonInputSuccess(logger, modelType.FullName); } } } diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs index 4d2b99d377c9..4d440a2dec56 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs @@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Mvc.Infrastructure { - internal sealed class SystemTextJsonResultExecutor : IActionResultExecutor + internal sealed partial class SystemTextJsonResultExecutor : IActionResultExecutor { private static readonly string DefaultContentType = new MediaTypeHeaderValue("application/json") { @@ -135,26 +135,21 @@ private JsonSerializerOptions GetSerializerOptions(JsonResult result) } } - private static class Log + private static partial class Log { - private static readonly LogDefineOptions SkipEnabledCheckLogOptions = new() { SkipEnabledCheck = true }; - - private static readonly Action _jsonResultExecuting = LoggerMessage.Define( - LogLevel.Information, - new EventId(1, "JsonResultExecuting"), - "Executing JsonResult, writing value of type '{Type}'.", - SkipEnabledCheckLogOptions); - - // EventId 2 BufferingAsyncEnumerable + [LoggerMessage(1, LogLevel.Information, "Executing JsonResult, writing value of type '{Type}'.", EventName = "JsonResultExecuting", SkipEnabledCheck = true)] + private static partial void JsonResultExecuting(ILogger logger, string? type); public static void JsonResultExecuting(ILogger logger, object? value) { if (logger.IsEnabled(LogLevel.Information)) { var type = value == null ? "null" : value.GetType().FullName; - _jsonResultExecuting(logger, type, null); + JsonResultExecuting(logger, type); } } + + // EventId 2 BufferingAsyncEnumerable } } } diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinder.cs index 1f1946bcd410..64a3a6f98c25 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinder.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders /// /// implementation for binding complex types. /// - public sealed class ComplexObjectModelBinder : IModelBinder + public sealed partial class ComplexObjectModelBinder : IModelBinder { // Don't want a new public enum because communication between the private and internal methods of this class // should not be exposed. Can't use an internal enum because types of [TheoryData] values must be public. @@ -740,16 +740,15 @@ private static void AddModelError( } } - private static class Log + private static partial class Log { - private static readonly Action _noPublicSettableProperties = LoggerMessage.Define( - LogLevel.Debug, - new EventId(17, "NoPublicSettableItems"), - "Could not bind to model with name '{ModelName}' and type '{ModelType}' as the type has no public settable properties or constructor parameters."); + [LoggerMessage(17, LogLevel.Debug, "Could not bind to model with name '{ModelName}' and type '{ModelType}' as the type has no " + + "public settable properties or constructor parameters.", EventName = "NoPublicSettableItems")] + public static partial void NoPublicSettableItems(ILogger logger, string modelName, Type modelType); public static void NoPublicSettableItems(ILogger logger, ModelBindingContext bindingContext) { - _noPublicSettableProperties(logger, bindingContext.ModelName, bindingContext.ModelType, null); + NoPublicSettableItems(logger, bindingContext.ModelName, bindingContext.ModelType); } } } diff --git a/src/Mvc/Mvc.Cors/src/CorsLoggerExtensions.cs b/src/Mvc/Mvc.Cors/src/CorsLoggerExtensions.cs index 8dba0a31e06b..91d481f01696 100644 --- a/src/Mvc/Mvc.Cors/src/CorsLoggerExtensions.cs +++ b/src/Mvc/Mvc.Cors/src/CorsLoggerExtensions.cs @@ -6,21 +6,9 @@ namespace Microsoft.AspNetCore.Mvc.Cors { - internal static class CorsLoggerExtensions + internal static partial class CorsLoggerExtensions { - private static readonly Action _notMostEffectiveFilter; - - static CorsLoggerExtensions() - { - _notMostEffectiveFilter = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "NotMostEffectiveFilter"), - "Skipping the execution of current filter as its not the most effective filter implementing the policy {FilterPolicy}."); - } - - public static void NotMostEffectiveFilter(this ILogger logger, Type policyType) - { - _notMostEffectiveFilter(logger, policyType, null); - } + [LoggerMessage(1, LogLevel.Debug, "Skipping the execution of current filter as its not the most effective filter implementing the policy {FilterPolicy}.", EventName = "NotMostEffectiveFilter")] + public static partial void NotMostEffectiveFilter(this ILogger logger, Type filterPolicy); } } diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs index df274511ceae..27c160561e97 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs @@ -11,24 +11,14 @@ namespace Microsoft.AspNetCore.Mvc.ApplicationModels { - internal class PageRouteModelFactory + internal sealed partial class PageRouteModelFactory { - private static readonly Action _unsupportedAreaPath; - private static readonly string IndexFileName = "Index" + RazorViewEngine.ViewExtension; private readonly RazorPagesOptions _options; private readonly ILogger _logger; private readonly string _normalizedRootDirectory; private readonly string _normalizedAreaRootDirectory; - static PageRouteModelFactory() - { - _unsupportedAreaPath = LoggerMessage.Define( - LogLevel.Warning, - new EventId(1, "UnsupportedAreaPath"), - "The page at '{FilePath}' is located under the area root directory '/Areas/' but does not follow the path format '/Areas/AreaName/Pages/Directory/FileName.cshtml"); - } - public PageRouteModelFactory( RazorPagesOptions options, ILogger logger) @@ -106,7 +96,7 @@ internal bool TryParseAreaPath( areaRootEndIndex >= relativePath.Length - 1 || // There's at least one token after the area root. !relativePath.StartsWith(_normalizedAreaRootDirectory, StringComparison.OrdinalIgnoreCase)) // The path must start with area root. { - _unsupportedAreaPath(_logger, relativePath, null); + Log.UnsupportedAreaPath(_logger, relativePath); return false; } @@ -114,7 +104,7 @@ internal bool TryParseAreaPath( var areaEndIndex = relativePath.IndexOf('/', startIndex: areaRootEndIndex + 1); if (areaEndIndex == -1 || areaEndIndex == relativePath.Length) { - _unsupportedAreaPath(_logger, relativePath, null); + Log.UnsupportedAreaPath(_logger, relativePath); return false; } @@ -122,7 +112,7 @@ internal bool TryParseAreaPath( // Ensure the next token is the "Pages" directory if (string.Compare(relativePath, areaEndIndex, AreaPagesRoot, 0, AreaPagesRoot.Length, StringComparison.OrdinalIgnoreCase) != 0) { - _unsupportedAreaPath(_logger, relativePath, null); + Log.UnsupportedAreaPath(_logger, relativePath); return false; } @@ -193,5 +183,11 @@ private static string NormalizeDirectory(string directory) return directory; } + + private static partial class Log + { + [LoggerMessage(1, LogLevel.Warning, "The page at '{FilePath}' is located under the area root directory '/Areas/' but does not follow the path format '/Areas/AreaName/Pages/Directory/FileName.cshtml", EventName = "UnsupportedAreaPath")] + public static partial void UnsupportedAreaPath(ILogger log, string filePath); + } } } diff --git a/src/Mvc/Mvc.RazorPages/src/PageLoggerExtensions.cs b/src/Mvc/Mvc.RazorPages/src/PageLoggerExtensions.cs index 5c62b2ac21a7..cf9dbcc22d6a 100644 --- a/src/Mvc/Mvc.RazorPages/src/PageLoggerExtensions.cs +++ b/src/Mvc/Mvc.RazorPages/src/PageLoggerExtensions.cs @@ -13,104 +13,12 @@ namespace Microsoft.AspNetCore.Mvc.RazorPages { - internal static class PageLoggerExtensions + internal static partial class PageLoggerExtensions { public const string PageFilter = "Page Filter"; - private static readonly Action _pageModelFactoryExecuting; - private static readonly Action _pageModelFactoryExecuted; - private static readonly Action _pageFactoryExecuting; - private static readonly Action _pageFactoryExecuted; - private static readonly Action _handlerMethodExecuting; - private static readonly Action _implicitHandlerMethodExecuting; - private static readonly Action _handlerMethodExecutingWithArguments; - private static readonly Action _handlerMethodExecuted; - private static readonly Action _implicitHandlerMethodExecuted; - private static readonly Action _pageFilterShortCircuit; - private static readonly Action _notMostEffectiveFilter; - private static readonly Action _beforeExecutingMethodOnFilter; - private static readonly Action _afterExecutingMethodOnFilter; - - private static readonly LogDefineOptions SkipEnabledCheckLogOptions = new() { SkipEnabledCheck = true }; - - static PageLoggerExtensions() - { - // These numbers start at 101 intentionally to avoid conflict with the IDs used by ResourceInvoker. - - _pageModelFactoryExecuting = LoggerMessage.Define( - LogLevel.Debug, - new EventId(101, "ExecutingModelFactory"), - "Executing page model factory for page {Page} ({AssemblyName})", - SkipEnabledCheckLogOptions); - - _pageModelFactoryExecuted = LoggerMessage.Define( - LogLevel.Debug, - new EventId(102, "ExecutedModelFactory"), - "Executed page model factory for page {Page} ({AssemblyName})", - SkipEnabledCheckLogOptions); - - _pageFactoryExecuting = LoggerMessage.Define( - LogLevel.Debug, - new EventId(101, "ExecutingPageFactory"), - "Executing page factory for page {Page} ({AssemblyName})", - SkipEnabledCheckLogOptions); - - _pageFactoryExecuted = LoggerMessage.Define( - LogLevel.Debug, - new EventId(102, "ExecutedPageFactory"), - "Executed page factory for page {Page} ({AssemblyName})", - SkipEnabledCheckLogOptions); - - _handlerMethodExecuting = LoggerMessage.Define( - LogLevel.Information, - new EventId(101, "ExecutingHandlerMethod"), - "Executing handler method {HandlerName} - ModelState is {ValidationState}", - SkipEnabledCheckLogOptions); - - _handlerMethodExecutingWithArguments = LoggerMessage.Define( - LogLevel.Trace, - new EventId(103, "HandlerMethodExecutingWithArguments"), - "Executing handler method {HandlerName} with arguments ({Arguments})", - SkipEnabledCheckLogOptions); - - _handlerMethodExecuted = LoggerMessage.Define( - LogLevel.Information, - new EventId(102, "ExecutedHandlerMethod"), - "Executed handler method {HandlerName}, returned result {ActionResult}.", - SkipEnabledCheckLogOptions); - - _implicitHandlerMethodExecuting = LoggerMessage.Define( - LogLevel.Information, - new EventId(103, "ExecutingImplicitHandlerMethod"), - "Executing an implicit handler method - ModelState is {ValidationState}", - SkipEnabledCheckLogOptions); - - _implicitHandlerMethodExecuted = LoggerMessage.Define( - LogLevel.Information, - new EventId(104, "ExecutedImplicitHandlerMethod"), - "Executed an implicit handler method, returned result {ActionResult}.", - SkipEnabledCheckLogOptions); - - _pageFilterShortCircuit = LoggerMessage.Define( - LogLevel.Debug, - new EventId(3, "PageFilterShortCircuited"), - "Request was short circuited at page filter '{PageFilter}'."); - - _notMostEffectiveFilter = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "NotMostEffectiveFilter"), - "Skipping the execution of current filter as its not the most effective filter implementing the policy {FilterPolicy}."); - - _beforeExecutingMethodOnFilter = LoggerMessage.Define( - LogLevel.Trace, - new EventId(1, "BeforeExecutingMethodOnFilter"), - "{FilterType}: Before executing {Method} on filter {Filter}."); - - _afterExecutingMethodOnFilter = LoggerMessage.Define( - LogLevel.Trace, - new EventId(2, "AfterExecutingMethodOnFilter"), - "{FilterType}: After executing {Method} on filter {Filter}."); - } + [LoggerMessage(101, LogLevel.Debug, "Executing page model factory for page {Page} ({AssemblyName})", EventName = "ExecutingModelFactory", SkipEnabledCheck = true)] + private static partial void ExecutingPageModelFactory(this ILogger logger, string page, string assemblyName); public static void ExecutingPageModelFactory(this ILogger logger, PageContext context) { @@ -121,9 +29,12 @@ public static void ExecutingPageModelFactory(this ILogger logger, PageContext co var pageType = context.ActionDescriptor.PageTypeInfo.AsType(); var pageName = TypeNameHelper.GetTypeDisplayName(pageType); - _pageModelFactoryExecuting(logger, pageName, pageType.Assembly.GetName().Name, null); + ExecutingPageModelFactory(logger, pageName, pageType.Assembly.GetName().Name); } + [LoggerMessage(102, LogLevel.Debug, "Executed page model factory for page {Page} ({AssemblyName})", EventName = "ExecutedModelFactory", SkipEnabledCheck = true)] + private static partial void ExecutedPageModelFactory(this ILogger logger, string page, string assemblyName); + public static void ExecutedPageModelFactory(this ILogger logger, PageContext context) { if (!logger.IsEnabled(LogLevel.Debug)) @@ -133,9 +44,12 @@ public static void ExecutedPageModelFactory(this ILogger logger, PageContext con var pageType = context.ActionDescriptor.PageTypeInfo.AsType(); var pageName = TypeNameHelper.GetTypeDisplayName(pageType); - _pageModelFactoryExecuted(logger, pageName, pageType.Assembly.GetName().Name, null); + ExecutedPageModelFactory(logger, pageName, pageType.Assembly.GetName().Name); } + [LoggerMessage(103, LogLevel.Debug, "Executing page factory for page {Page} ({AssemblyName})", EventName = "ExecutingPageFactory", SkipEnabledCheck = true)] + private static partial void ExecutingPageFactory(this ILogger logger, string page, string assemblyName); + public static void ExecutingPageFactory(this ILogger logger, PageContext context) { if (!logger.IsEnabled(LogLevel.Debug)) @@ -145,9 +59,12 @@ public static void ExecutingPageFactory(this ILogger logger, PageContext context var pageType = context.ActionDescriptor.PageTypeInfo.AsType(); var pageName = TypeNameHelper.GetTypeDisplayName(pageType); - _pageFactoryExecuting(logger, pageName, pageType.Assembly.GetName().Name, null); + ExecutingPageFactory(logger, pageName, pageType.Assembly.GetName().Name); } + [LoggerMessage(104, LogLevel.Debug, "Executed page factory for page {Page} ({AssemblyName})", EventName = "ExecutedPageFactory", SkipEnabledCheck = true)] + private static partial void ExecutedPageFactory(this ILogger logger, string page, string assemblyName); + public static void ExecutedPageFactory(this ILogger logger, PageContext context) { if (!logger.IsEnabled(LogLevel.Debug)) @@ -157,9 +74,15 @@ public static void ExecutedPageFactory(this ILogger logger, PageContext context) var pageType = context.ActionDescriptor.PageTypeInfo.AsType(); var pageName = TypeNameHelper.GetTypeDisplayName(pageType); - _pageFactoryExecuted(logger, pageName, pageType.Assembly.GetName().Name, null); + ExecutedPageFactory(logger, pageName, pageType.Assembly.GetName().Name); } + [LoggerMessage(105, LogLevel.Information, "Executing handler method {HandlerName} - ModelState is {ValidationState}", EventName = "ExecutingHandlerMethod", SkipEnabledCheck = true)] + private static partial void ExecutingHandlerMethod(this ILogger logger, string handlerName, ModelValidationState validationState); + + [LoggerMessage(106, LogLevel.Trace, "Executing handler method {HandlerName} with arguments ({Arguments})", EventName = "HandlerMethodExecutingWithArguments", SkipEnabledCheck = true)] + private static partial void ExecutingHandlerMethodWithArguments(this ILogger logger, string handlerName, string[] arguments); + public static void ExecutingHandlerMethod(this ILogger logger, PageContext context, HandlerMethodDescriptor handler, object?[]? arguments) { if (logger.IsEnabled(LogLevel.Information)) @@ -168,7 +91,7 @@ public static void ExecutingHandlerMethod(this ILogger logger, PageContext conte var handlerName = declaringTypeName + "." + handler.MethodInfo.Name; var validationState = context.ModelState.ValidationState; - _handlerMethodExecuting(logger, handlerName, validationState, null); + ExecutingHandlerMethod(logger, handlerName, validationState); if (arguments != null && logger.IsEnabled(LogLevel.Trace)) { @@ -178,58 +101,59 @@ public static void ExecutingHandlerMethod(this ILogger logger, PageContext conte convertedArguments[i] = Convert.ToString(arguments[i], CultureInfo.InvariantCulture); } - _handlerMethodExecutingWithArguments(logger, handlerName, convertedArguments, null); + ExecutingHandlerMethodWithArguments(logger, handlerName, convertedArguments); } } } + [LoggerMessage(107, LogLevel.Information, "Executing an implicit handler method - ModelState is {ValidationState}", EventName = "ExecutingImplicitHandlerMethod", SkipEnabledCheck = true)] + public static partial void ExecutingImplicitHandlerMethod(this ILogger logger, ModelValidationState validationState); + public static void ExecutingImplicitHandlerMethod(this ILogger logger, PageContext context) { if (logger.IsEnabled(LogLevel.Information)) { var validationState = context.ModelState.ValidationState; - _implicitHandlerMethodExecuting(logger, validationState, null); + ExecutingImplicitHandlerMethod(logger, validationState); } } + [LoggerMessage(108, LogLevel.Information, "Executed handler method {HandlerName}, returned result {ActionResult}.", EventName = "ExecutedHandlerMethod")] + public static partial void ExecutedHandlerMethod(this ILogger logger, string handlerName, string? actionResult); + public static void ExecutedHandlerMethod(this ILogger logger, PageContext context, HandlerMethodDescriptor handler, IActionResult? result) { if (logger.IsEnabled(LogLevel.Information)) { var handlerName = handler.MethodInfo.Name; - _handlerMethodExecuted(logger, handlerName, Convert.ToString(result, CultureInfo.InvariantCulture), null); + ExecutedHandlerMethod(logger, handlerName, Convert.ToString(result, CultureInfo.InvariantCulture)); } } + [LoggerMessage(109, LogLevel.Information, "Executed an implicit handler method, returned result {ActionResult}.", EventName = "ExecutedImplicitHandlerMethod", SkipEnabledCheck = true)] + public static partial void ExecutedImplicitHandlerMethod(this ILogger logger, string actionResult); + public static void ExecutedImplicitHandlerMethod(this ILogger logger, IActionResult result) { if (logger.IsEnabled(LogLevel.Information)) { - _implicitHandlerMethodExecuted(logger, Convert.ToString(result, CultureInfo.InvariantCulture), null); + ExecutedImplicitHandlerMethod(logger, Convert.ToString(result, CultureInfo.InvariantCulture)); } } - public static void BeforeExecutingMethodOnFilter(this ILogger logger, string filterType, string methodName, IFilterMetadata filter) - { - _beforeExecutingMethodOnFilter(logger, filterType, methodName, filter.GetType().ToString(), null); - } + [LoggerMessage(1, LogLevel.Trace, "{FilterType}: Before executing {Method} on filter {Filter}.", EventName = "BeforeExecutingMethodOnFilter")] + public static partial void BeforeExecutingMethodOnFilter(this ILogger logger, string filterType, string method, IFilterMetadata filter); - public static void AfterExecutingMethodOnFilter(this ILogger logger, string filterType, string methodName, IFilterMetadata filter) - { - _afterExecutingMethodOnFilter(logger, filterType, methodName, filter.GetType().ToString(), null); - } + [LoggerMessage(2, LogLevel.Trace, "{FilterType}: After executing {Method} on filter {Filter}.", EventName = "AfterExecutingMethodOnFilter")] + public static partial void AfterExecutingMethodOnFilter(this ILogger logger, string filterType, string method, IFilterMetadata filter); - public static void PageFilterShortCircuited( + [LoggerMessage(3, LogLevel.Debug, "Request was short circuited at page filter '{PageFilter}'.", EventName = "PageFilterShortCircuited")] + public static partial void PageFilterShortCircuited( this ILogger logger, - IFilterMetadata filter) - { - _pageFilterShortCircuit(logger, filter, null); - } + IFilterMetadata pageFilter); - public static void NotMostEffectiveFilter(this ILogger logger, Type policyType) - { - _notMostEffectiveFilter(logger, policyType, null); - } + [LoggerMessage(4, LogLevel.Debug, "Skipping the execution of current filter as its not the most effective filter implementing the policy {FilterPolicy}.", EventName = "NotMostEffectiveFilter")] + public static partial void NotMostEffectiveFilter(this ILogger logger, Type filterPolicy); } }