diff --git a/.editorconfig b/.editorconfig index 332a3377e1cf..1066556ba091 100644 --- a/.editorconfig +++ b/.editorconfig @@ -91,6 +91,9 @@ dotnet_diagnostic.CA1802.severity = warning # CA1805: Do not initialize unnecessarily dotnet_diagnostic.CA1805.severity = warning +# CA1810: Do not initialize unnecessarily +dotnet_diagnostic.CA1810.severity = suggestion + # CA1823: Remove empty Finalizers dotnet_diagnostic.CA1821.severity = warning diff --git a/eng/Versions.props b/eng/Versions.props index 50eb391033fe..490858981176 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -95,7 +95,7 @@ 6.0.0-preview.6.21314.2 6.0.0-preview.6.21314.2 6.0.0-preview.6.21314.2 - 6.0.0-preview.6.21314.2 + 6.0.0-preview.7.21316.3 6.0.0-preview.6.21314.2 6.0.0-preview.6.21314.2 6.0.0-preview.6.21314.2 diff --git a/src/Components/Web/src/Forms/InputNumber.cs b/src/Components/Web/src/Forms/InputNumber.cs index ec73e52164cc..6e84f715759e 100644 --- a/src/Components/Web/src/Forms/InputNumber.cs +++ b/src/Components/Web/src/Forms/InputNumber.cs @@ -14,9 +14,9 @@ namespace Microsoft.AspNetCore.Components.Forms /// public class InputNumber<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TValue> : InputBase { - private readonly static string _stepAttributeValue; // Null by default, so only allows whole numbers as per HTML spec + private static readonly string _stepAttributeValue = GetStepAttributeValue(); - static InputNumber() + private static string GetStepAttributeValue() { // Unwrap Nullable, because InputBase already deals with the Nullable aspect // of it for us. We will only get asked to parse the T for nonempty inputs. @@ -28,7 +28,7 @@ static InputNumber() targetType == typeof(double) || targetType == typeof(decimal)) { - _stepAttributeValue = "any"; + return "any"; } else { diff --git a/src/Components/WebAssembly/WebAssembly/src/Rendering/RendererRegistry.cs b/src/Components/WebAssembly/WebAssembly/src/Rendering/RendererRegistry.cs index 31a063992435..56d4246e23fe 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Rendering/RendererRegistry.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Rendering/RendererRegistry.cs @@ -13,16 +13,8 @@ internal static class RendererRegistry // as well as rooting them for GC purposes, since nothing would otherwise be referencing // them even though we might still receive incoming events from JS. + private static readonly Dictionary? _renderers = OperatingSystem.IsBrowser() ? new() : null; private static int _nextId; - private static Dictionary? _renderers; - - static RendererRegistry() - { - if (OperatingSystem.IsBrowser()) - { - _renderers = new Dictionary(); - } - } internal static WebAssemblyRenderer Find(int rendererId) { diff --git a/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs b/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs index 672edcbb59bb..b4bad110aedf 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs @@ -163,21 +163,16 @@ protected override void HandleException(Exception exception) private static class Log { - private static readonly Action _unhandledExceptionRenderingComponent; + 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"); } - static Log() - { - _unhandledExceptionRenderingComponent = LoggerMessage.Define( - LogLevel.Critical, - EventIds.UnhandledExceptionRenderingComponent, - "Unhandled exception rendering component: {Message}"); - } - public static void UnhandledExceptionRenderingComponent(ILogger logger, Exception exception) { _unhandledExceptionRenderingComponent( diff --git a/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs b/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs index 8acd0ceda678..fd4e12403c33 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs @@ -13,20 +13,13 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Services internal class WebAssemblyConsoleLogger : ILogger, ILogger { private const string _loglevelPadding = ": "; - private static readonly string _messagePadding; - private static readonly string _newLineWithMessagePadding; + private static readonly string _messagePadding = new(' ', GetLogLevelString(LogLevel.Information).Length + _loglevelPadding.Length); + private static readonly string _newLineWithMessagePadding = Environment.NewLine + _messagePadding; private static readonly StringBuilder _logBuilder = new StringBuilder(); private readonly string _name; private readonly WebAssemblyJSRuntime _jsRuntime; - static WebAssemblyConsoleLogger() - { - var logLevelString = GetLogLevelString(LogLevel.Information); - _messagePadding = new string(' ', logLevelString.Length + _loglevelPadding.Length); - _newLineWithMessagePadding = Environment.NewLine + _messagePadding; - } - public WebAssemblyConsoleLogger(IJSRuntime jsRuntime) : this(string.Empty, (WebAssemblyJSRuntime)jsRuntime) // Cast for DI { diff --git a/src/Hosting/Hosting/src/Internal/HostingLoggerExtensions.cs b/src/Hosting/Hosting/src/Internal/HostingLoggerExtensions.cs index 7dcf39bce16c..b9e89692e2fd 100644 --- a/src/Hosting/Hosting/src/Internal/HostingLoggerExtensions.cs +++ b/src/Hosting/Hosting/src/Internal/HostingLoggerExtensions.cs @@ -11,28 +11,18 @@ namespace Microsoft.AspNetCore.Hosting { - internal static class HostingLoggerExtensions + internal static partial class HostingLoggerExtensions { - private static readonly Action _startupAssemblyLoaded = - LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.HostingStartupAssemblyLoaded, "Loaded hosting startup assembly {assemblyName}", skipEnabledCheck: true); - - private static readonly Action _listeningOnAddress = - LoggerMessage.Define(LogLevel.Information, LoggerEventIds.ServerListeningOnAddresses, "Now listening on: {address}"); - public static IDisposable RequestScope(this ILogger logger, HttpContext httpContext) { return logger.BeginScope(new HostingLogScope(httpContext)); } - public static void ListeningOnAddress(this ILogger logger, string address) - { - _listeningOnAddress(logger, address, null); - } + [LoggerMessage(EventId = LoggerEventIds.ServerListeningOnAddresses, EventName = "ServerListeningOnAddresses", Level = LogLevel.Information, Message = "Now listening on: {address}")] + public static partial void ListeningOnAddress(this ILogger logger, string address); - public static void StartupAssemblyLoaded(this ILogger logger, string assemblyName) - { - _startupAssemblyLoaded(logger, assemblyName, null); - } + [LoggerMessage(EventId = LoggerEventIds.HostingStartupAssemblyLoaded, EventName = "HostingStartupAssemblyLoaded", Level = LogLevel.Debug, Message = "Loaded hosting startup assembly {assemblyName}")] + public static partial void StartupAssemblyLoaded(this ILogger logger, string assemblyName); public static void ApplicationError(this ILogger logger, Exception exception) { diff --git a/src/Hosting/Hosting/src/Internal/LoggerEventIds.cs b/src/Hosting/Hosting/src/Internal/LoggerEventIds.cs index da4bdd9f60c0..916eeae6a2d8 100644 --- a/src/Hosting/Hosting/src/Internal/LoggerEventIds.cs +++ b/src/Hosting/Hosting/src/Internal/LoggerEventIds.cs @@ -1,24 +1,23 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Hosting { internal static class LoggerEventIds { - public static readonly EventId RequestStarting = new EventId(1, "RequestStarting"); - public static readonly EventId RequestFinished = new EventId(2, "RequestFinished"); - public static readonly EventId Starting = new EventId(3, "Starting"); - public static readonly EventId Started = new EventId(4, "Started"); - public static readonly EventId Shutdown = new EventId(5, "Shutdown"); - public static readonly EventId ApplicationStartupException = new EventId(6, "ApplicationStartupException"); - public static readonly EventId ApplicationStoppingException = new EventId(7, "ApplicationStoppingException"); - public static readonly EventId ApplicationStoppedException = new EventId(8, "ApplicationStoppedException"); - public static readonly EventId HostedServiceStartException = new EventId(9, "HostedServiceStartException"); - public static readonly EventId HostedServiceStopException = new EventId(10, "HostedServiceStopException"); - public static readonly EventId HostingStartupAssemblyException = new EventId(11, "HostingStartupAssemblyException"); - public static readonly EventId ServerShutdownException = new EventId(12, "ServerShutdownException"); - public static readonly EventId HostingStartupAssemblyLoaded = new EventId(13, "HostingStartupAssemblyLoaded"); - public static readonly EventId ServerListeningOnAddresses = new EventId(14, "ServerListeningOnAddresses"); + public const int RequestStarting = 1; + public const int RequestFinished = 2; + public const int Starting = 3; + public const int Started = 4; + public const int Shutdown = 5; + public const int ApplicationStartupException = 6; + public const int ApplicationStoppingException = 7; + public const int ApplicationStoppedException = 8; + public const int HostedServiceStartException = 9; + public const int HostedServiceStopException = 10; + public const int HostingStartupAssemblyException = 11; + public const int ServerShutdownException = 12; + public const int HostingStartupAssemblyLoaded = 13; + public const int ServerListeningOnAddresses = 14; } } diff --git a/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj b/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj index 9babc9ec30e6..38f79972a27c 100644 --- a/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj +++ b/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj @@ -19,6 +19,7 @@ Microsoft.AspNetCore.Http.HttpResponse + diff --git a/src/Http/Http.Extensions/src/Microsoft.AspNetCore.Http.Extensions.csproj b/src/Http/Http.Extensions/src/Microsoft.AspNetCore.Http.Extensions.csproj index 94a3e73732a3..6eae60ee8936 100644 --- a/src/Http/Http.Extensions/src/Microsoft.AspNetCore.Http.Extensions.csproj +++ b/src/Http/Http.Extensions/src/Microsoft.AspNetCore.Http.Extensions.csproj @@ -19,6 +19,7 @@ + diff --git a/src/Http/Http.Extensions/src/RequestDelegateFactory.cs b/src/Http/Http.Extensions/src/RequestDelegateFactory.cs index b14ef5fb3d40..5e3d45b6d9ad 100644 --- a/src/Http/Http.Extensions/src/RequestDelegateFactory.cs +++ b/src/Http/Http.Extensions/src/RequestDelegateFactory.cs @@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.Http /// /// Creates implementations from request handlers. /// - public static class RequestDelegateFactory + public static partial class RequestDelegateFactory { private static readonly MethodInfo ExecuteTaskOfTMethod = typeof(RequestDelegateFactory).GetMethod(nameof(ExecuteTask), BindingFlags.NonPublic | BindingFlags.Static)!; private static readonly MethodInfo ExecuteTaskOfStringMethod = typeof(RequestDelegateFactory).GetMethod(nameof(ExecuteTaskOfString), BindingFlags.NonPublic | BindingFlags.Static)!; @@ -809,37 +809,25 @@ private class FactoryContext public List<(ParameterExpression, Expression)> TryParseParams { get; } = new(); } - private static class Log + private static partial class Log { - private static readonly Action _requestBodyIOException = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "RequestBodyIOException"), - "Reading the request body failed with an IOException."); + public static void RequestBodyIOException(HttpContext httpContext, Exception exception) + => RequestBodyIOException(GetLogger(httpContext), exception); - private static readonly Action _requestBodyInvalidDataException = LoggerMessage.Define( - LogLevel.Debug, - new EventId(2, "RequestBodyInvalidDataException"), - "Reading the request body failed with an InvalidDataException."); - - private static readonly Action _parameterBindingFailed = LoggerMessage.Define( - LogLevel.Debug, - new EventId(3, "ParamaterBindingFailed"), - @"Failed to bind parameter ""{ParameterType} {ParameterName}"" from ""{SourceValue}""."); - - public static void RequestBodyIOException(HttpContext httpContext, IOException exception) - { - _requestBodyIOException(GetLogger(httpContext), exception); - } + [LoggerMessage(EventId = 1, EventName = "RequestBodyIOException", Level = LogLevel.Debug, Message = "Reading the request body failed with an IOException.")] + public static partial void RequestBodyIOException(ILogger logger, Exception exception); public static void RequestBodyInvalidDataException(HttpContext httpContext, InvalidDataException exception) - { - _requestBodyInvalidDataException(GetLogger(httpContext), exception); - } + => RequestBodyInvalidDataException(GetLogger(httpContext), exception); + + [LoggerMessage(EventId = 2, EventName = "RequestBodyInvalidDataException", Level = LogLevel.Debug, Message = "Reading the request body failed with an InvalidDataException.")] + public static partial void RequestBodyInvalidDataException(ILogger logger, InvalidDataException exception); public static void ParameterBindingFailed(HttpContext httpContext, string parameterTypeName, string parameterName, string sourceValue) - { - _parameterBindingFailed(GetLogger(httpContext), parameterTypeName, parameterName, sourceValue, null); - } + => ParameterBindingFailed(GetLogger(httpContext), parameterTypeName, parameterName, sourceValue); + + [LoggerMessage(EventId = 3, EventName = "ParamaterBindingFailed", Level = LogLevel.Debug, Message = @"Failed to bind parameter ""{ParameterType} {ParameterName}"" from ""{SourceValue}"".")] + public static partial void ParameterBindingFailed(ILogger logger, string parameterType, string parameterName, string sourceValue); private static ILogger GetLogger(HttpContext httpContext) { diff --git a/src/Http/Http/src/Internal/ResponseCookies.cs b/src/Http/Http/src/Internal/ResponseCookies.cs index c2068821df51..6affe6d9084d 100644 --- a/src/Http/Http/src/Internal/ResponseCookies.cs +++ b/src/Http/Http/src/Internal/ResponseCookies.cs @@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Http /// /// A wrapper for the response Set-Cookie header. /// - internal class ResponseCookies : IResponseCookies + internal sealed partial class ResponseCookies : IResponseCookies { internal const string EnableCookieNameEncoding = "Microsoft.AspNetCore.Http.EnableCookieNameEncoding"; internal bool _enableCookieNameEncoding = AppContext.TryGetSwitch(EnableCookieNameEncoding, out var enabled) && enabled; @@ -212,17 +212,10 @@ public void Delete(string key, CookieOptions options) }); } - private static class Log + private static partial class Log { - private static readonly Action _samesiteNotSecure = LoggerMessage.Define( - LogLevel.Warning, - EventIds.SameSiteNotSecure, - "The cookie '{name}' has set 'SameSite=None' and must also set 'Secure'."); - - public static void SameSiteCookieNotSecure(ILogger logger, string name) - { - _samesiteNotSecure(logger, name, null); - } + [LoggerMessage(EventId = 1, EventName = "SameSiteNotSecure", Level = LogLevel.Warning, Message = "The cookie '{name}' has set 'SameSite=None' and must also set 'Secure'.")] + public static partial void SameSiteCookieNotSecure(ILogger logger, string name); } } } diff --git a/src/Http/Routing/src/DefaultLinkGenerator.cs b/src/Http/Routing/src/DefaultLinkGenerator.cs index b285ac6b5de3..474c6337dc4a 100644 --- a/src/Http/Routing/src/DefaultLinkGenerator.cs +++ b/src/Http/Routing/src/DefaultLinkGenerator.cs @@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Routing { - internal sealed class DefaultLinkGenerator : LinkGenerator, IDisposable + internal sealed partial class DefaultLinkGenerator : LinkGenerator, IDisposable { private readonly ParameterPolicyFactory _parameterPolicyFactory; private readonly TemplateBinderFactory _binderFactory; @@ -336,137 +336,91 @@ public void Dispose() } #nullable disable - private static class Log + private static partial class Log { - public static class EventIds - { - public static readonly EventId EndpointsFound = new EventId(100, "EndpointsFound"); - public static readonly EventId EndpointsNotFound = new EventId(101, "EndpointsNotFound"); - - public static readonly EventId TemplateSucceeded = new EventId(102, "TemplateSucceeded"); - public static readonly EventId TemplateFailedRequiredValues = new EventId(103, "TemplateFailedRequiredValues"); - public static readonly EventId TemplateFailedConstraint = new EventId(103, "TemplateFailedConstraint"); - public static readonly EventId TemplateFailedExpansion = new EventId(104, "TemplateFailedExpansion"); + [LoggerMessage(EventId = 100, EventName = "EndpointsFound", Level = LogLevel.Debug, Message = "Found the endpoints {Endpoints} for address {Address}")] + public static partial void EndpointsFound(ILogger logger, object address, IEnumerable endpoints); - public static readonly EventId LinkGenerationSucceeded = new EventId(105, "LinkGenerationSucceeded"); - public static readonly EventId LinkGenerationFailed = new EventId(106, "LinkGenerationFailed"); - } - - private static readonly Action, object, Exception> _endpointsFound = LoggerMessage.Define, object>( - LogLevel.Debug, - EventIds.EndpointsFound, - "Found the endpoints {Endpoints} for address {Address}", - skipEnabledCheck: true); - - private static readonly Action _endpointsNotFound = LoggerMessage.Define( - LogLevel.Debug, - EventIds.EndpointsNotFound, - "No endpoints found for address {Address}"); - - private static readonly Action _templateSucceeded = LoggerMessage.Define( - LogLevel.Debug, - EventIds.TemplateSucceeded, - "Successfully processed template {Template} for {Endpoint} resulting in {Path} and {Query}"); - - private static readonly Action _templateFailedRequiredValues = LoggerMessage.Define( - LogLevel.Debug, - EventIds.TemplateFailedRequiredValues, - "Failed to process the template {Template} for {Endpoint}. " + - "A required route value is missing, or has a different value from the required default values. " + - "Supplied ambient values {AmbientValues} and {Values} with default values {Defaults}", - skipEnabledCheck: true); - - private static readonly Action _templateFailedConstraint = LoggerMessage.Define( - LogLevel.Debug, - EventIds.TemplateFailedConstraint, - "Failed to process the template {Template} for {Endpoint}. " + - "The constraint {Constraint} for parameter {ParameterName} failed with values {Values}", - skipEnabledCheck: true); - - private static readonly Action _templateFailedExpansion = LoggerMessage.Define( - LogLevel.Debug, - EventIds.TemplateFailedExpansion, - "Failed to process the template {Template} for {Endpoint}. " + - "The failure occurred while expanding the template with values {Values} " + - "This is usually due to a missing or empty value in a complex segment", - skipEnabledCheck: true); - - private static readonly Action, string, Exception> _linkGenerationSucceeded = LoggerMessage.Define, string>( - LogLevel.Debug, - EventIds.LinkGenerationSucceeded, - "Link generation succeeded for endpoints {Endpoints} with result {URI}", - skipEnabledCheck: true); - - private static readonly Action, Exception> _linkGenerationFailed = LoggerMessage.Define>( - LogLevel.Debug, - EventIds.LinkGenerationFailed, - "Link generation failed for endpoints {Endpoints}", - skipEnabledCheck: true); - - public static void EndpointsFound(ILogger logger, object address, IEnumerable endpoints) - { - // Checking level again to avoid allocation on the common path - if (logger.IsEnabled(LogLevel.Debug)) - { - _endpointsFound(logger, endpoints.Select(e => e.DisplayName), address, null); - } - } - - public static void EndpointsNotFound(ILogger logger, object address) - { - _endpointsNotFound(logger, address, null); - } + [LoggerMessage(EventId = 101, EventName = "EndpointsNotFound", Level = LogLevel.Debug, Message = "No endpoints found for address {Address}")] + public static partial void EndpointsNotFound(ILogger logger, object address); public static void TemplateSucceeded(ILogger logger, RouteEndpoint endpoint, PathString path, QueryString query) - { - _templateSucceeded(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, path.Value, query.Value, null); - } + => TemplateSucceeded(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, path.Value, query.Value); + + [LoggerMessage(EventId = 102, EventName = "TemplateSucceeded", Level = LogLevel.Debug, + Message = "Successfully processed template {Template} for {Endpoint} resulting in {Path} and {Query}")] + public static partial void TemplateSucceeded(ILogger logger, string template, string endpoint, string path, string query); public static void TemplateFailedRequiredValues(ILogger logger, RouteEndpoint endpoint, RouteValueDictionary ambientValues, RouteValueDictionary values) { // Checking level again to avoid allocation on the common path if (logger.IsEnabled(LogLevel.Debug)) { - _templateFailedRequiredValues(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, FormatRouteValues(ambientValues), FormatRouteValues(values), FormatRouteValues(endpoint.RoutePattern.Defaults), null); + TemplateFailedRequiredValues(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, FormatRouteValues(ambientValues), FormatRouteValues(values), FormatRouteValues(endpoint.RoutePattern.Defaults)); } } + [LoggerMessage(EventId = 103, EventName = "TemplateFailedRequiredValues", Level = LogLevel.Debug, + Message = "Failed to process the template {Template} for {Endpoint}. " + + "A required route value is missing, or has a different value from the required default values. " + + "Supplied ambient values {AmbientValues} and {Values} with default values {Defaults}")] + public static partial void TemplateFailedRequiredValues(ILogger logger, string template, string endpoint, string ambientValues, string values, string defaults); + public static void TemplateFailedConstraint(ILogger logger, RouteEndpoint endpoint, string parameterName, IRouteConstraint constraint, RouteValueDictionary values) { // Checking level again to avoid allocation on the common path if (logger.IsEnabled(LogLevel.Debug)) { - _templateFailedConstraint(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, constraint, parameterName, FormatRouteValues(values), null); + TemplateFailedConstraint(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, parameterName, constraint, FormatRouteValues(values)); } } + [LoggerMessage(EventId = 107, EventName = "TemplateFailedConstraint", Level = LogLevel.Debug, + Message = "Failed to process the template {Template} for {Endpoint}. " + + "The constraint {Constraint} for parameter {ParameterName} failed with values {Values}")] + public static partial void TemplateFailedConstraint(ILogger logger, string template, string endpoint, string parameterName, IRouteConstraint constraint, string values); + public static void TemplateFailedExpansion(ILogger logger, RouteEndpoint endpoint, RouteValueDictionary values) { // Checking level again to avoid allocation on the common path if (logger.IsEnabled(LogLevel.Debug)) { - _templateFailedExpansion(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, FormatRouteValues(values), null); + TemplateFailedExpansion(logger, endpoint.RoutePattern.RawText, endpoint.DisplayName, FormatRouteValues(values)); } } + [LoggerMessage(EventId = 104, EventName = "TemplateFailedExpansion", Level = LogLevel.Debug, + Message = "Failed to process the template {Template} for {Endpoint}. " + + "The failure occurred while expanding the template with values {Values} " + + "This is usually due to a missing or empty value in a complex segment")] + public static partial void TemplateFailedExpansion(ILogger logger, string template, string endpoint, string values); + public static void LinkGenerationSucceeded(ILogger logger, IEnumerable endpoints, string uri) { // Checking level again to avoid allocation on the common path if (logger.IsEnabled(LogLevel.Debug)) { - _linkGenerationSucceeded(logger, endpoints.Select(e => e.DisplayName), uri, null); + LinkGenerationSucceeded(logger, endpoints.Select(e => e.DisplayName), uri); } } + [LoggerMessage(EventId = 105, EventName = "LinkGenerationSucceeded", Level = LogLevel.Debug, + Message = "Link generation succeeded for endpoints {Endpoints} with result {URI}")] + public static partial void LinkGenerationSucceeded(ILogger logger, IEnumerable endpoints, string uri); + public static void LinkGenerationFailed(ILogger logger, IEnumerable endpoints) { // Checking level again to avoid allocation on the common path if (logger.IsEnabled(LogLevel.Debug)) { - _linkGenerationFailed(logger, endpoints.Select(e => e.DisplayName), null); + LinkGenerationFailed(logger, endpoints.Select(e => e.DisplayName)); } } + [LoggerMessage(EventId = 106, EventName = "LinkGenerationFailed", Level = LogLevel.Debug, + Message = "Link generation failed for endpoints {Endpoints}")] + public static partial void LinkGenerationFailed(ILogger logger, IEnumerable endpoints); + // EXPENSIVE: should only be used at Debug and higher levels of logging. private static string FormatRouteValues(IReadOnlyDictionary values) { diff --git a/src/Http/Routing/src/Logging/RouteConstraintMatcherExtensions.cs b/src/Http/Routing/src/Logging/RouteConstraintMatcherExtensions.cs index 9415831bdc02..cfd3b1a00b2c 100644 --- a/src/Http/Routing/src/Logging/RouteConstraintMatcherExtensions.cs +++ b/src/Http/Routing/src/Logging/RouteConstraintMatcherExtensions.cs @@ -8,16 +8,11 @@ namespace Microsoft.AspNetCore.Routing.Logging { internal static class RouteConstraintMatcherExtensions { - private static readonly Action _constraintNotMatched; - - static RouteConstraintMatcherExtensions() - { - _constraintNotMatched = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "ConstraintNotMatched"), - "Route value '{RouteValue}' with key '{RouteKey}' did not match " + - "the constraint '{RouteConstraint}'"); - } + private static readonly Action _constraintNotMatched = LoggerMessage.Define( + LogLevel.Debug, + new EventId(1, "ConstraintNotMatched"), + "Route value '{RouteValue}' with key '{RouteKey}' did not match " + + "the constraint '{RouteConstraint}'"); public static void ConstraintNotMatched( this ILogger logger, diff --git a/src/Http/Routing/src/Logging/RouterMiddlewareLoggerExtensions.cs b/src/Http/Routing/src/Logging/RouterMiddlewareLoggerExtensions.cs index 76f569c1508f..a83ae01b50f0 100644 --- a/src/Http/Routing/src/Logging/RouterMiddlewareLoggerExtensions.cs +++ b/src/Http/Routing/src/Logging/RouterMiddlewareLoggerExtensions.cs @@ -8,15 +8,10 @@ namespace Microsoft.AspNetCore.Routing.Logging { internal static class RouterMiddlewareLoggerExtensions { - private static readonly Action _requestNotMatched; - - static RouterMiddlewareLoggerExtensions() - { - _requestNotMatched = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "RequestNotMatched"), - "Request did not match any routes"); - } + private static readonly Action _requestNotMatched = LoggerMessage.Define( + LogLevel.Debug, + new EventId(1, "RequestNotMatched"), + "Request did not match any routes"); public static void RequestNotMatched(this ILogger logger) { diff --git a/src/Http/Routing/src/Logging/TreeRouterLoggerExtensions.cs b/src/Http/Routing/src/Logging/TreeRouterLoggerExtensions.cs index bcb0f343a779..a67b3b54f0d6 100644 --- a/src/Http/Routing/src/Logging/TreeRouterLoggerExtensions.cs +++ b/src/Http/Routing/src/Logging/TreeRouterLoggerExtensions.cs @@ -8,15 +8,10 @@ namespace Microsoft.AspNetCore.Routing.Logging { internal static class TreeRouterLoggerExtensions { - private static readonly Action _requestMatchedRoute; - - static TreeRouterLoggerExtensions() - { - _requestMatchedRoute = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "RequestMatchedRoute"), - "Request successfully matched the route with name '{RouteName}' and template '{RouteTemplate}'"); - } + private static readonly Action _requestMatchedRoute = LoggerMessage.Define( + LogLevel.Debug, + new EventId(1, "RequestMatchedRoute"), + "Request successfully matched the route with name '{RouteName}' and template '{RouteTemplate}'"); public static void RequestMatchedRoute( this ILogger logger, diff --git a/src/Localization/Localization/src/Internal/ResourceManagerStringLocalizerLoggerExtensions.cs b/src/Localization/Localization/src/Internal/ResourceManagerStringLocalizerLoggerExtensions.cs index 67d244f26521..8900dbe00eb5 100644 --- a/src/Localization/Localization/src/Internal/ResourceManagerStringLocalizerLoggerExtensions.cs +++ b/src/Localization/Localization/src/Internal/ResourceManagerStringLocalizerLoggerExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -9,15 +9,10 @@ namespace Microsoft.Extensions.Localization.Internal { internal static class ResourceManagerStringLocalizerLoggerExtensions { - private static readonly Action _searchedLocation; - - static ResourceManagerStringLocalizerLoggerExtensions() - { - _searchedLocation = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "SearchedLocation"), - $"{nameof(ResourceManagerStringLocalizer)} searched for '{{Key}}' in '{{LocationSearched}}' with culture '{{Culture}}'."); - } + private static readonly Action _searchedLocation = LoggerMessage.Define( + LogLevel.Debug, + new EventId(1, "SearchedLocation"), + $"{nameof(ResourceManagerStringLocalizer)} searched for '{{Key}}' in '{{LocationSearched}}' with culture '{{Culture}}'."); public static void SearchedLocation(this ILogger logger, string key, string searchedLocation, CultureInfo culture) { diff --git a/src/Middleware/CORS/src/CORSLoggerExtensions.cs b/src/Middleware/CORS/src/CORSLoggerExtensions.cs index a1747a8994c4..1baf530e2c56 100644 --- a/src/Middleware/CORS/src/CORSLoggerExtensions.cs +++ b/src/Middleware/CORS/src/CORSLoggerExtensions.cs @@ -6,131 +6,40 @@ namespace Microsoft.AspNetCore.Cors { - internal static class CORSLoggerExtensions + internal static partial class CORSLoggerExtensions { - private static readonly Action _isPreflightRequest; - private static readonly Action _requestHasOriginHeader; - private static readonly Action _requestDoesNotHaveOriginHeader; - private static readonly Action _policySuccess; - private static readonly Action _policyFailure; - private static readonly Action _originNotAllowed; - private static readonly Action _accessControlMethodNotAllowed; - private static readonly Action _requestHeaderNotAllowed; - private static readonly Action _failedToSetCorsHeaders; - private static readonly Action _noCorsPolicyFound; - private static readonly Action _isNotPreflightRequest; + [LoggerMessage(EventId = 1, EventName = "IsPreflightRequest", Level = LogLevel.Debug, Message = "The request is a preflight request.")] + public static partial void IsPreflightRequest(this ILogger logger); - static CORSLoggerExtensions() - { - _isPreflightRequest = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "IsPreflightRequest"), - "The request is a preflight request."); + [LoggerMessage(EventId = 2, EventName = "RequestHasOriginHeader", Level = LogLevel.Debug, Message = "The request has an origin header: '{origin}'.")] + public static partial void RequestHasOriginHeader(this ILogger logger, string origin); - _requestHasOriginHeader = LoggerMessage.Define( - LogLevel.Debug, - new EventId(2, "RequestHasOriginHeader"), - "The request has an origin header: '{origin}'."); + [LoggerMessage(EventId = 3, EventName = "RequestDoesNotHaveOriginHeader", Level = LogLevel.Debug, Message = "The request does not have an origin header.")] + public static partial void RequestDoesNotHaveOriginHeader(this ILogger logger); - _requestDoesNotHaveOriginHeader = LoggerMessage.Define( - LogLevel.Debug, - new EventId(3, "RequestDoesNotHaveOriginHeader"), - "The request does not have an origin header."); + [LoggerMessage(EventId = 4, EventName = "PolicySuccess", Level = LogLevel.Information, Message = "CORS policy execution successful.")] + public static partial void PolicySuccess(this ILogger logger); - _policySuccess = LoggerMessage.Define( - LogLevel.Information, - new EventId(4, "PolicySuccess"), - "CORS policy execution successful."); + [LoggerMessage(EventId = 5, EventName = "PolicyFailure", Level = LogLevel.Information, Message = "CORS policy execution failed.")] + public static partial void PolicyFailure(this ILogger logger); - _policyFailure = LoggerMessage.Define( - LogLevel.Information, - new EventId(5, "PolicyFailure"), - "CORS policy execution failed."); + [LoggerMessage(EventId = 6, EventName = "OriginNotAllowed", Level = LogLevel.Information, Message = "Request origin {origin} does not have permission to access the resource.")] + public static partial void OriginNotAllowed(this ILogger logger, string origin); - _originNotAllowed = LoggerMessage.Define( - LogLevel.Information, - new EventId(6, "OriginNotAllowed"), - "Request origin {origin} does not have permission to access the resource."); + [LoggerMessage(EventId = 7, EventName = "AccessControlMethodNotAllowed", Level = LogLevel.Information, Message = "Request method {accessControlRequestMethod} not allowed in CORS policy.")] + public static partial void AccessControlMethodNotAllowed(this ILogger logger, string accessControlMethod); - _accessControlMethodNotAllowed = LoggerMessage.Define( - LogLevel.Information, - new EventId(7, "AccessControlMethodNotAllowed"), - "Request method {accessControlRequestMethod} not allowed in CORS policy."); + [LoggerMessage(EventId = 8, EventName = "RequestHeaderNotAllowed", Level = LogLevel.Information, Message = "Request header '{requestHeader}' not allowed in CORS policy.")] + public static partial void RequestHeaderNotAllowed(this ILogger logger, string requestHeader); - _requestHeaderNotAllowed = LoggerMessage.Define( - LogLevel.Information, - new EventId(8, "RequestHeaderNotAllowed"), - "Request header '{requestHeader}' not allowed in CORS policy."); + [LoggerMessage(EventId = 9, EventName = "FailedToSetCorsHeaders", Level = LogLevel.Warning, Message = "Failed to apply CORS Response headers.")] + public static partial void FailedToSetCorsHeaders(this ILogger logger, Exception? exception); - _failedToSetCorsHeaders = LoggerMessage.Define( - LogLevel.Warning, - new EventId(9, "FailedToSetCorsHeaders"), - "Failed to apply CORS Response headers."); + [LoggerMessage(EventId = 10, EventName = "NoCorsPolicyFound", Level = LogLevel.Information, Message = "No CORS policy found for the specified request.")] + public static partial void NoCorsPolicyFound(this ILogger logger); - _noCorsPolicyFound = LoggerMessage.Define( - LogLevel.Information, - new EventId(10, "NoCorsPolicyFound"), - "No CORS policy found for the specified request."); - - _isNotPreflightRequest = LoggerMessage.Define( - LogLevel.Debug, - new EventId(12, "IsNotPreflightRequest"), - "This request uses the HTTP OPTIONS method but does not have an Access-Control-Request-Method header. This request will not be treated as a CORS preflight request."); - } - - public static void IsPreflightRequest(this ILogger logger) - { - _isPreflightRequest(logger, null); - } - - public static void RequestHasOriginHeader(this ILogger logger, string origin) - { - _requestHasOriginHeader(logger, origin, null); - } - - public static void RequestDoesNotHaveOriginHeader(this ILogger logger) - { - _requestDoesNotHaveOriginHeader(logger, null); - } - - public static void PolicySuccess(this ILogger logger) - { - _policySuccess(logger, null); - } - - public static void PolicyFailure(this ILogger logger) - { - _policyFailure(logger, null); - } - - public static void OriginNotAllowed(this ILogger logger, string origin) - { - _originNotAllowed(logger, origin, null); - } - - public static void AccessControlMethodNotAllowed(this ILogger logger, string accessControlMethod) - { - _accessControlMethodNotAllowed(logger, accessControlMethod, null); - } - - public static void RequestHeaderNotAllowed(this ILogger logger, string requestHeader) - { - _requestHeaderNotAllowed(logger, requestHeader, null); - } - - public static void FailedToSetCorsHeaders(this ILogger logger, Exception? exception) - { - _failedToSetCorsHeaders(logger, exception); - } - - public static void NoCorsPolicyFound(this ILogger logger) - { - _noCorsPolicyFound(logger, null); - } - - public static void IsNotPreflightRequest(this ILogger logger) - { - _isNotPreflightRequest(logger, null); - } + [LoggerMessage(EventId = 12, EventName = "IsNotPreflightRequest", Level = LogLevel.Debug, + Message = "This request uses the HTTP OPTIONS method but does not have an Access-Control-Request-Method header. This request will not be treated as a CORS preflight request.")] + public static partial void IsNotPreflightRequest(this ILogger logger); } } diff --git a/src/Middleware/HttpOverrides/src/LoggingExtensions.cs b/src/Middleware/HttpOverrides/src/LoggingExtensions.cs index 61f2f1b51fe9..873c27c15bd8 100644 --- a/src/Middleware/HttpOverrides/src/LoggingExtensions.cs +++ b/src/Middleware/HttpOverrides/src/LoggingExtensions.cs @@ -7,15 +7,10 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _noCertificate; - - static LoggingExtensions() - { - _noCertificate = LoggerMessage.Define( - eventId: new EventId(0, "NoCertificate"), - logLevel: LogLevel.Warning, - formatString: "Could not read certificate from header."); - } + private static Action _noCertificate = LoggerMessage.Define( + eventId: new EventId(0, "NoCertificate"), + logLevel: LogLevel.Warning, + formatString: "Could not read certificate from header."); public static void NoCertificate(this ILogger logger, Exception exception) { diff --git a/src/Middleware/HttpsPolicy/src/HstsLoggingExtensions.cs b/src/Middleware/HttpsPolicy/src/HstsLoggingExtensions.cs index 7fcaa1ea2e55..5ddc8e85b0ce 100644 --- a/src/Middleware/HttpsPolicy/src/HstsLoggingExtensions.cs +++ b/src/Middleware/HttpsPolicy/src/HstsLoggingExtensions.cs @@ -8,27 +8,18 @@ namespace Microsoft.AspNetCore.HttpsPolicy { internal static class HstsLoggingExtensions { - private static readonly Action _notSecure; - private static readonly Action _excludedHost; - private static readonly Action _addingHstsHeader; - - static HstsLoggingExtensions() - { - _notSecure = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "NotSecure"), - "The request is insecure. Skipping HSTS header."); - - _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."); - } + private static readonly Action _notSecure = LoggerMessage.Define( + LogLevel.Debug, + new EventId(1, "NotSecure"), + "The request is insecure. Skipping HSTS header."); + private static readonly Action _excludedHost = LoggerMessage.Define( + LogLevel.Debug, + new EventId(2, "ExcludedHost"), + "The host '{host}' is excluded. Skipping HSTS header."); + private static readonly Action _addingHstsHeader = LoggerMessage.Define( + LogLevel.Trace, + new EventId(3, "AddingHstsHeader"), + "Adding HSTS header to response."); public static void SkippingInsecure(this ILogger logger) { diff --git a/src/Middleware/HttpsPolicy/src/HttpsLoggingExtensions.cs b/src/Middleware/HttpsPolicy/src/HttpsLoggingExtensions.cs index f3b00416f566..36e33093813e 100644 --- a/src/Middleware/HttpsPolicy/src/HttpsLoggingExtensions.cs +++ b/src/Middleware/HttpsPolicy/src/HttpsLoggingExtensions.cs @@ -8,33 +8,25 @@ namespace Microsoft.AspNetCore.HttpsPolicy { internal static class HttpsLoggingExtensions { - private static readonly Action _redirectingToHttps; - private static readonly Action _portLoadedFromConfig; - private static readonly Action _failedToDeterminePort; - private static readonly Action _portFromServer; - - static HttpsLoggingExtensions() - { - _redirectingToHttps = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "RedirectingToHttps"), - "Redirecting to '{redirect}'."); - - _portLoadedFromConfig = LoggerMessage.Define( - LogLevel.Debug, - new EventId(2, "PortLoadedFromConfig"), - "Https port '{port}' loaded from configuration."); - - _failedToDeterminePort = LoggerMessage.Define( - LogLevel.Warning, - new EventId(3, "FailedToDeterminePort"), - "Failed to determine the https port for redirect."); - - _portFromServer = LoggerMessage.Define( + private static readonly Action _redirectingToHttps = LoggerMessage.Define( + LogLevel.Debug, + new EventId(1, "RedirectingToHttps"), + "Redirecting to '{redirect}'."); + + private static readonly Action _portLoadedFromConfig = LoggerMessage.Define( + LogLevel.Debug, + new EventId(2, "PortLoadedFromConfig"), + "Https port '{port}' loaded from configuration."); + + private static readonly Action _failedToDeterminePort = LoggerMessage.Define( + LogLevel.Warning, + new EventId(3, "FailedToDeterminePort"), + "Failed to determine the https port for redirect."); + + private static readonly Action _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) { diff --git a/src/Middleware/Localization/src/RequestCultureProviderLoggerExtensions.cs b/src/Middleware/Localization/src/RequestCultureProviderLoggerExtensions.cs index d7af673e74bd..d78f62ff8f7e 100644 --- a/src/Middleware/Localization/src/RequestCultureProviderLoggerExtensions.cs +++ b/src/Middleware/Localization/src/RequestCultureProviderLoggerExtensions.cs @@ -10,20 +10,14 @@ namespace Microsoft.AspNetCore.Localization { internal static 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>( + private static readonly Action, Exception?> _unsupportedCulture = LoggerMessage.Define>( + LogLevel.Debug, + new EventId(1, "UnsupportedCulture"), + "{requestCultureProvider} returned the following unsupported cultures '{cultures}'."); + private static readonly Action, Exception?> _unsupportedUICulture = LoggerMessage.Define>( LogLevel.Debug, new EventId(2, "UnsupportedUICulture"), "{requestCultureProvider} returned the following unsupported UI Cultures '{uiCultures}'."); - } public static void UnsupportedCultures(this ILogger logger, string requestCultureProvider, IList cultures) { diff --git a/src/Middleware/ResponseCaching/src/FastGuid.cs b/src/Middleware/ResponseCaching/src/FastGuid.cs index e54b61106d2e..0aba388e1a38 100644 --- a/src/Middleware/ResponseCaching/src/FastGuid.cs +++ b/src/Middleware/ResponseCaching/src/FastGuid.cs @@ -11,7 +11,7 @@ internal class FastGuid // Base32 encoding - in ascii sort order for easy text based sorting private static readonly char[] s_encode32Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUV".ToCharArray(); // Global ID - private static long NextId; + private static long NextId = InitializeNextId(); // Instance components private string? _idString; @@ -31,12 +31,12 @@ internal string IdString } // Static constructor to initialize global components - static FastGuid() + private static long InitializeNextId() { var guidBytes = Guid.NewGuid().ToByteArray(); // Use the first 4 bytes from the Guid to initialize global ID - NextId = + return guidBytes[0] << 32 | guidBytes[1] << 40 | guidBytes[2] << 48 | diff --git a/src/Middleware/StaticFiles/src/LoggerExtensions.cs b/src/Middleware/StaticFiles/src/LoggerExtensions.cs index b2d973bff61b..2df0fc00fc2c 100644 --- a/src/Middleware/StaticFiles/src/LoggerExtensions.cs +++ b/src/Middleware/StaticFiles/src/LoggerExtensions.cs @@ -10,145 +10,45 @@ namespace Microsoft.AspNetCore.StaticFiles /// /// Defines *all* the logger messages produced by static files /// - internal static class LoggerExtensions + internal static partial class LoggerExtensions { - private static Action _methodNotSupported; - private static Action _fileServed; - private static Action _pathMismatch; - private static Action _fileTypeNotSupported; - private static Action _fileNotFound; - private static Action _fileNotModified; - private static Action _preconditionFailed; - private static Action _handled; - private static Action _rangeNotSatisfiable; - private static Action _sendingFileRange; - private static Action _copyingFileRange; - private static Action _writeCancelled; - private static Action _endpointMatched; + [LoggerMessage(EventId = 1, EventName = "MethodNotSupported", Level = LogLevel.Debug, Message = "{Method} requests are not supported")] + public static partial void RequestMethodNotSupported(this ILogger logger, string method); - static LoggerExtensions() - { - _methodNotSupported = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(1, "MethodNotSupported"), - formatString: "{Method} requests are not supported"); - _fileServed = LoggerMessage.Define( - logLevel: LogLevel.Information, - eventId: new EventId(2, "FileServed"), - formatString: "Sending file. Request path: '{VirtualPath}'. Physical path: '{PhysicalPath}'"); - _pathMismatch = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(3, "PathMismatch"), - formatString: "The request path {Path} does not match the path filter"); - _fileTypeNotSupported = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(4, "FileTypeNotSupported"), - formatString: "The request path {Path} does not match a supported file type"); - _fileNotFound = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(5, "FileNotFound"), - formatString: "The request path {Path} does not match an existing file"); - _fileNotModified = LoggerMessage.Define( - logLevel: LogLevel.Information, - eventId: new EventId(6, "FileNotModified"), - formatString: "The file {Path} was not modified"); - _preconditionFailed = LoggerMessage.Define( - logLevel: LogLevel.Information, - eventId: new EventId(7, "PreconditionFailed"), - formatString: "Precondition for {Path} failed"); - _handled = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(8, "Handled"), - formatString: "Handled. Status code: {StatusCode} File: {Path}"); - _rangeNotSatisfiable = LoggerMessage.Define( - logLevel: LogLevel.Warning, - eventId: new EventId(9, "RangeNotSatisfiable"), - formatString: "Range not satisfiable for {Path}"); - _sendingFileRange = LoggerMessage.Define( - logLevel: LogLevel.Information, - eventId: new EventId(10, "SendingFileRange"), - formatString: "Sending {Range} of file {Path}"); - _copyingFileRange = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(11, "CopyingFileRange"), - formatString: "Copying {Range} of file {Path} to the response body"); - _writeCancelled = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(14, "WriteCancelled"), - formatString: "The file transmission was cancelled"); - _endpointMatched = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(15, "EndpointMatched"), - formatString: "Static files was skipped as the request already matched an endpoint."); - } + [LoggerMessage(EventId = 2, EventName = "FileServed", Level = LogLevel.Debug, Message = "Sending file. Request path: '{VirtualPath}'. Physical path: '{PhysicalPath}'")] + public static partial void FileServed(this ILogger logger, string virtualPath, string physicalPath); - public static void RequestMethodNotSupported(this ILogger logger, string method) - { - _methodNotSupported(logger, method, null); - } + [LoggerMessage(EventId = 15, EventName = "EndpointMatched", Level = LogLevel.Debug, Message = "Static files was skipped as the request already matched an endpoint.")] + public static partial void EndpointMatched(this ILogger logger); - public static void FileServed(this ILogger logger, string virtualPath, string physicalPath) - { - if (string.IsNullOrEmpty(physicalPath)) - { - physicalPath = "N/A"; - } - _fileServed(logger, virtualPath, physicalPath, null); - } + [LoggerMessage(EventId = 3, EventName = "PathMismatch", Level = LogLevel.Debug, Message = "The request path {Path} does not match the path filter")] + public static partial void PathMismatch(this ILogger logger, string path); - public static void EndpointMatched(this ILogger logger) - { - _endpointMatched(logger, null); - } + [LoggerMessage(EventId = 4, EventName = "FileTypeNotSupported", Level = LogLevel.Debug, Message = "The request path {Path} does not match a supported file type")] + public static partial void FileTypeNotSupported(this ILogger logger, string path); - public static void PathMismatch(this ILogger logger, string path) - { - _pathMismatch(logger, path, null); - } + [LoggerMessage(EventId = 5, EventName = "FileNotFound", Level = LogLevel.Debug, Message = "The request path {Path} does not match an existing file")] + public static partial void FileNotFound(this ILogger logger, string path); - public static void FileTypeNotSupported(this ILogger logger, string path) - { - _fileTypeNotSupported(logger, path, null); - } + [LoggerMessage(EventId = 6, EventName = "FileNotModified", Level = LogLevel.Information, Message = "The file {Path} was not modified")] + public static partial void FileNotModified(this ILogger logger, string path); - public static void FileNotFound(this ILogger logger, string path) - { - _fileNotFound(logger, path, null); - } + [LoggerMessage(EventId = 7, EventName = "PreconditionFailed", Level = LogLevel.Information, Message = "Precondition for {Path} failed")] + public static partial void PreconditionFailed(this ILogger logger, string path); - public static void FileNotModified(this ILogger logger, string path) - { - _fileNotModified(logger, path, null); - } + [LoggerMessage(EventId = 8, EventName = "Handled", Level = LogLevel.Debug, Message = "Handled. Status code: {StatusCode} File: {Path}")] + public static partial void Handled(this ILogger logger, int statusCode, string path); - public static void PreconditionFailed(this ILogger logger, string path) - { - _preconditionFailed(logger, path, null); - } + [LoggerMessage(EventId = 9, EventName = "RangeNotSatisfiable", Level = LogLevel.Warning, Message = "Range not satisfiable for {Path}")] + public static partial void RangeNotSatisfiable(this ILogger logger, string path); - public static void Handled(this ILogger logger, int statusCode, string path) - { - _handled(logger, statusCode, path, null); - } + [LoggerMessage(EventId = 10, EventName = "SendingFileRange", Level = LogLevel.Information, Message = "Sending {Range} of file {Path}")] + public static partial void SendingFileRange(this ILogger logger, StringValues range, string path); - public static void RangeNotSatisfiable(this ILogger logger, string path) - { - _rangeNotSatisfiable(logger, path, null); - } + [LoggerMessage(EventId = 11, EventName = "CopyingFileRange", Level = LogLevel.Debug, Message = "Copying {Range} of file {Path} to the response body")] + public static partial void CopyingFileRange(this ILogger logger, StringValues range, string path); - public static void SendingFileRange(this ILogger logger, StringValues range, string path) - { - _sendingFileRange(logger, range, path, null); - } - - public static void CopyingFileRange(this ILogger logger, StringValues range, string path) - { - _copyingFileRange(logger, range, path, null); - } - - public static void WriteCancelled(this ILogger logger, Exception ex) - { - _writeCancelled(logger, ex); - } + [LoggerMessage(EventId = 14, EventName = "WriteCancelled", Level = LogLevel.Debug, Message = "The file transmission was cancelled")] + public static partial void WriteCancelled(this ILogger logger, Exception ex); } } diff --git a/src/Middleware/StaticFiles/src/StaticFileContext.cs b/src/Middleware/StaticFiles/src/StaticFileContext.cs index 5b787ef3f9b4..55482a20c15c 100644 --- a/src/Middleware/StaticFiles/src/StaticFileContext.cs +++ b/src/Middleware/StaticFiles/src/StaticFileContext.cs @@ -313,7 +313,8 @@ public async Task ServeStaticFile(HttpContext context, RequestDelegate next) } await SendAsync(); - _logger.FileServed(SubPath, PhysicalPath); + var loggedPath = string.IsNullOrEmpty(PhysicalPath) ? "N/A" : PhysicalPath; + _logger.FileServed(SubPath, loggedPath); return; } catch (FileNotFoundException) diff --git a/src/Mvc/Mvc.Core/src/Formatters/HttpTokenParsingRules.cs b/src/Mvc/Mvc.Core/src/Formatters/HttpTokenParsingRules.cs index db9f8f444c6e..b7ad2fada752 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/HttpTokenParsingRules.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/HttpTokenParsingRules.cs @@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters { internal static class HttpTokenParsingRules { - private static readonly bool[] TokenChars; + private static readonly bool[] TokenChars = CreateTokenChars(); private const int MaxNestedCount = 5; internal const char CR = '\r'; @@ -21,36 +21,38 @@ internal static class HttpTokenParsingRules // iso-8859-1, Western European (ISO) internal static readonly Encoding DefaultHttpEncoding = Encoding.GetEncoding(28591); - static HttpTokenParsingRules() + private static bool[] CreateTokenChars() { // token = 1* // CTL = - TokenChars = new bool[128]; // everything is false + var tokenChars = new bool[128]; // everything is false - for (int i = 33; i < 127; i++) // skip Space (32) & DEL (127) + for (var i = 33; i < 127; i++) // skip Space (32) & DEL (127) { - TokenChars[i] = true; + tokenChars[i] = true; } // remove separators: these are not valid token characters - TokenChars[(byte)'('] = false; - TokenChars[(byte)')'] = false; - TokenChars[(byte)'<'] = false; - TokenChars[(byte)'>'] = false; - TokenChars[(byte)'@'] = false; - TokenChars[(byte)','] = false; - TokenChars[(byte)';'] = false; - TokenChars[(byte)':'] = false; - TokenChars[(byte)'\\'] = false; - TokenChars[(byte)'"'] = false; - TokenChars[(byte)'/'] = false; - TokenChars[(byte)'['] = false; - TokenChars[(byte)']'] = false; - TokenChars[(byte)'?'] = false; - TokenChars[(byte)'='] = false; - TokenChars[(byte)'{'] = false; - TokenChars[(byte)'}'] = false; + tokenChars[(byte)'('] = false; + tokenChars[(byte)')'] = false; + tokenChars[(byte)'<'] = false; + tokenChars[(byte)'>'] = false; + tokenChars[(byte)'@'] = false; + tokenChars[(byte)','] = false; + tokenChars[(byte)';'] = false; + tokenChars[(byte)':'] = false; + tokenChars[(byte)'\\'] = false; + tokenChars[(byte)'"'] = false; + tokenChars[(byte)'/'] = false; + tokenChars[(byte)'['] = false; + tokenChars[(byte)']'] = false; + tokenChars[(byte)'?'] = false; + tokenChars[(byte)'='] = false; + tokenChars[(byte)'{'] = false; + tokenChars[(byte)'}'] = false; + + return tokenChars; } internal static bool IsTokenChar(char character) diff --git a/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs b/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs index 37e78b7ca9d1..7a498f6f32fd 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs @@ -146,20 +146,15 @@ private Exception WrapExceptionForModelState(JsonException jsonException) private static class Log { - private static readonly Action _jsonInputFormatterException; - private static readonly Action _jsonInputSuccess; - - static Log() - { - _jsonInputFormatterException = LoggerMessage.Define( + private static readonly Action _jsonInputFormatterException = LoggerMessage.Define( LogLevel.Debug, new EventId(1, "SystemTextJsonInputException"), "JSON input formatter threw an exception: {Message}"); - _jsonInputSuccess = LoggerMessage.Define( + + private static readonly Action _jsonInputSuccess = LoggerMessage.Define( LogLevel.Debug, new EventId(2, "SystemTextJsonInputSuccess"), "JSON input formatter succeeded, deserializing to type '{TypeName}'"); - } public static void JsonInputException(ILogger logger, Exception exception) => _jsonInputFormatterException(logger, exception.Message, exception); diff --git a/src/Mvc/Mvc.Cors/src/CorsLoggerExtensions.cs b/src/Mvc/Mvc.Cors/src/CorsLoggerExtensions.cs index ccba2a65e4c9..09f0a3fef2d6 100644 --- a/src/Mvc/Mvc.Cors/src/CorsLoggerExtensions.cs +++ b/src/Mvc/Mvc.Cors/src/CorsLoggerExtensions.cs @@ -8,15 +8,10 @@ namespace Microsoft.AspNetCore.Mvc.Cors { internal static class CorsLoggerExtensions { - private static readonly Action _notMostEffectiveFilter; - - static CorsLoggerExtensions() - { - _notMostEffectiveFilter = LoggerMessage.Define( + private static readonly Action _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) { diff --git a/src/Mvc/Mvc.Formatters.Xml/src/LoggerExtensions.cs b/src/Mvc/Mvc.Formatters.Xml/src/LoggerExtensions.cs index 3bb43de3c169..88f931d10396 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/LoggerExtensions.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/LoggerExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -8,21 +8,15 @@ namespace Microsoft.AspNetCore.Mvc.Formatters.Xml { internal static class LoggerExtensions { - private static readonly Action _failedToCreateXmlSerializer; - private static readonly Action _failedToCreateDataContractSerializer; + private static readonly Action _failedToCreateXmlSerializer = LoggerMessage.Define( + LogLevel.Warning, + new EventId(1, "FailedToCreateXmlSerializer"), + "An error occurred while trying to create an XmlSerializer for the type '{Type}'."); - static LoggerExtensions() - { - _failedToCreateXmlSerializer = LoggerMessage.Define( - LogLevel.Warning, - new EventId(1, "FailedToCreateXmlSerializer"), - "An error occurred while trying to create an XmlSerializer for the type '{Type}'."); - - _failedToCreateDataContractSerializer = LoggerMessage.Define( - LogLevel.Warning, - new EventId(2, "FailedToCreateDataContractSerializer"), - "An error occurred while trying to create a DataContractSerializer for the type '{Type}'."); - } + private static readonly Action _failedToCreateDataContractSerializer = LoggerMessage.Define( + LogLevel.Warning, + new EventId(2, "FailedToCreateDataContractSerializer"), + "An error occurred while trying to create a DataContractSerializer for the type '{Type}'."); public static void FailedToCreateXmlSerializer(this ILogger logger, string typeName, Exception exception) { diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/JsonSerializerSettingsProvider.cs b/src/Mvc/Mvc.NewtonsoftJson/src/JsonSerializerSettingsProvider.cs index cc9521087832..9a62c7bc3119 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/JsonSerializerSettingsProvider.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/JsonSerializerSettingsProvider.cs @@ -17,12 +17,7 @@ public static class JsonSerializerSettingsProvider // return shared resolver by default for perf so slow reflection logic is cached once // developers can set their own resolver after the settings are returned if desired - private static readonly DefaultContractResolver SharedContractResolver; - - static JsonSerializerSettingsProvider() - { - SharedContractResolver = CreateContractResolver(); - } + private static readonly DefaultContractResolver SharedContractResolver = CreateContractResolver(); /// /// Creates default . diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonLoggerExtensions.cs b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonLoggerExtensions.cs index c1089748899c..d62f6f3842dc 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonLoggerExtensions.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonLoggerExtensions.cs @@ -8,15 +8,10 @@ namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson { internal static class NewtonsoftJsonLoggerExtensions { - private static readonly Action _jsonInputFormatterException; - - static NewtonsoftJsonLoggerExtensions() - { - _jsonInputFormatterException = LoggerMessage.Define( - LogLevel.Debug, - new EventId(1, "JsonInputException"), - "JSON input formatter threw an exception."); - } + private static readonly Action _jsonInputFormatterException = LoggerMessage.Define( + LogLevel.Debug, + new EventId(1, "JsonInputException"), + "JSON input formatter threw an exception."); public static void JsonInputException(this ILogger logger, Exception exception) { diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs index ebfe1667bf2f..f64aa43508c3 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModelFactory.cs @@ -13,7 +13,10 @@ namespace Microsoft.AspNetCore.Mvc.ApplicationModels { internal class PageRouteModelFactory { - private static readonly Action _unsupportedAreaPath; + private static readonly Action _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"); private static readonly string IndexFileName = "Index" + RazorViewEngine.ViewExtension; private readonly RazorPagesOptions _options; @@ -21,14 +24,6 @@ internal class PageRouteModelFactory 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) diff --git a/src/Mvc/Mvc.TagHelpers/src/MvcTagHelpersLoggerExtensions.cs b/src/Mvc/Mvc.TagHelpers/src/MvcTagHelpersLoggerExtensions.cs index 9cae27c52908..7c32836aee8a 100644 --- a/src/Mvc/Mvc.TagHelpers/src/MvcTagHelpersLoggerExtensions.cs +++ b/src/Mvc/Mvc.TagHelpers/src/MvcTagHelpersLoggerExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -8,15 +8,10 @@ namespace Microsoft.AspNetCore.Mvc.TagHelpers { internal static class MvcTagHelperLoggerExtensions { - private static readonly Action _distributedFormatterDeserializedFailed; - - static MvcTagHelperLoggerExtensions() - { - _distributedFormatterDeserializedFailed = LoggerMessage.Define( - LogLevel.Error, - new EventId(1, "DistributedFormatterDeserializationException"), - "Couldn't deserialize cached value for key {Key}."); - } + private static readonly Action _distributedFormatterDeserializedFailed = LoggerMessage.Define( + LogLevel.Error, + new EventId(1, "DistributedFormatterDeserializationException"), + "Couldn't deserialize cached value for key {Key}."); public static void DistributedFormatterDeserializationException(this ILogger logger, string key, Exception exception) { diff --git a/src/Security/Authentication/Cookies/src/LoggingExtensions.cs b/src/Security/Authentication/Cookies/src/LoggingExtensions.cs index 340fb04a2958..c1b420afc4ff 100644 --- a/src/Security/Authentication/Cookies/src/LoggingExtensions.cs +++ b/src/Security/Authentication/Cookies/src/LoggingExtensions.cs @@ -7,20 +7,14 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _authenticationSchemeSignedIn; - private static Action _authenticationSchemeSignedOut; - - static LoggingExtensions() - { - _authenticationSchemeSignedIn = LoggerMessage.Define( + private static readonly Action _authenticationSchemeSignedIn = LoggerMessage.Define( eventId: new EventId(10, "AuthenticationSchemeSignedIn"), logLevel: LogLevel.Information, formatString: "AuthenticationScheme: {AuthenticationScheme} signed in."); - _authenticationSchemeSignedOut = LoggerMessage.Define( + private static readonly Action _authenticationSchemeSignedOut = LoggerMessage.Define( eventId: new EventId(11, "AuthenticationSchemeSignedOut"), logLevel: LogLevel.Information, formatString: "AuthenticationScheme: {AuthenticationScheme} signed out."); - } public static void AuthenticationSchemeSignedIn(this ILogger logger, string authenticationScheme) { diff --git a/src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs b/src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs index 2767122d1b96..d17ab79bab0b 100644 --- a/src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs +++ b/src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs @@ -7,25 +7,18 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _tokenValidationFailed; - private static Action _tokenValidationSucceeded; - private static Action _errorProcessingMessage; - - static LoggingExtensions() - { - _tokenValidationFailed = LoggerMessage.Define( - eventId: new EventId(1, "TokenValidationFailed"), - logLevel: LogLevel.Information, - formatString: "Failed to validate the token."); - _tokenValidationSucceeded = LoggerMessage.Define( + 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."); - _errorProcessingMessage = LoggerMessage.Define( + private static readonly Action _errorProcessingMessage = LoggerMessage.Define( eventId: new EventId(3, "ProcessingMessageFailed"), logLevel: LogLevel.Error, formatString: "Exception occurred while processing message."); - } public static void TokenValidationFailed(this ILogger logger, Exception ex) => _tokenValidationFailed(logger, ex); diff --git a/src/Security/Authorization/Core/src/LoggingExtensions.cs b/src/Security/Authorization/Core/src/LoggingExtensions.cs index 15ef9ca8d171..026a6894b77c 100644 --- a/src/Security/Authorization/Core/src/LoggingExtensions.cs +++ b/src/Security/Authorization/Core/src/LoggingExtensions.cs @@ -8,20 +8,15 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _userAuthorizationFailed; - private static Action _userAuthorizationSucceeded; + private static readonly Action _userAuthorizationFailed = LoggerMessage.Define( + eventId: new EventId(2, "UserAuthorizationFailed"), + logLevel: LogLevel.Information, + formatString: "Authorization failed. {0}"); - static LoggingExtensions() - { - _userAuthorizationSucceeded = LoggerMessage.Define( - eventId: new EventId(1, "UserAuthorizationSucceeded"), - logLevel: LogLevel.Debug, - formatString: "Authorization was successful."); - _userAuthorizationFailed = LoggerMessage.Define( - eventId: new EventId(2, "UserAuthorizationFailed"), - logLevel: LogLevel.Information, - formatString: "Authorization failed. {0}"); - } + private static readonly Action _userAuthorizationSucceeded = LoggerMessage.Define( + eventId: new EventId(1, "UserAuthorizationSucceeded"), + logLevel: LogLevel.Debug, + formatString: "Authorization was successful."); public static void UserAuthorizationSucceeded(this ILogger logger) => _userAuthorizationSucceeded(logger, null); diff --git a/src/Servers/HttpSys/src/NativeInterop/ComNetOS.cs b/src/Servers/HttpSys/src/NativeInterop/ComNetOS.cs index f2b693c1d150..5d4705fe58f6 100644 --- a/src/Servers/HttpSys/src/NativeInterop/ComNetOS.cs +++ b/src/Servers/HttpSys/src/NativeInterop/ComNetOS.cs @@ -9,13 +9,6 @@ internal static class ComNetOS { // Windows is assumed based on HttpApi.Supported which is checked in the HttpSysListener constructor. // Minimum support for Windows 7 is assumed. - internal static readonly bool IsWin8orLater; - - static ComNetOS() - { - var win8Version = new Version(6, 2); - - IsWin8orLater = (Environment.OSVersion.Version >= win8Version); - } + internal static readonly bool IsWin8orLater = OperatingSystem.IsWindowsVersionAtLeast(6, 2); } } diff --git a/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs b/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs index dc92a42ee46f..07f898670c5f 100644 --- a/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs +++ b/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs @@ -11,18 +11,18 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting.IIS // Uses Windows Job Objects to ensure external processes are killed if the current process is terminated non-gracefully. internal static class ProcessTracker { - private static readonly IntPtr _jobHandle; + private static readonly IntPtr _jobHandle = IntiailizeProcessTracker(); - static ProcessTracker() + private static IntPtr IntiailizeProcessTracker() { // Requires Win8 or later if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || Environment.OSVersion.Version < new Version(6, 2)) { - return; + return IntPtr.Zero; } // Job name is optional but helps with diagnostics. Job name must be unique if non-null. - _jobHandle = CreateJobObject(IntPtr.Zero, name: $"ProcessTracker{Environment.ProcessId}"); + var jobHandle = CreateJobObject(IntPtr.Zero, name: $"ProcessTracker{Environment.ProcessId}"); var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION { @@ -38,7 +38,7 @@ static ProcessTracker() { Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false); - if (!SetInformationJobObject(_jobHandle, JobObjectInfoType.ExtendedLimitInformation, + if (!SetInformationJobObject(jobHandle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length)) { throw new Win32Exception(); @@ -48,6 +48,8 @@ static ProcessTracker() { Marshal.FreeHGlobal(extendedInfoPtr); } + + return jobHandle; } public static void Add(Process process) diff --git a/src/Shared/StackTrace/ExceptionDetails/LoggerExtensions.cs b/src/Shared/StackTrace/ExceptionDetails/LoggerExtensions.cs index 17ef3a944c6b..989c59869469 100644 --- a/src/Shared/StackTrace/ExceptionDetails/LoggerExtensions.cs +++ b/src/Shared/StackTrace/ExceptionDetails/LoggerExtensions.cs @@ -6,21 +6,9 @@ namespace Microsoft.Extensions.StackTrace.Sources { - internal static class LoggerExtensions + internal static partial class LoggerExtensions { - private static readonly Action _failedToReadStackFrameInfo; - - static LoggerExtensions() - { - _failedToReadStackFrameInfo = LoggerMessage.Define( - logLevel: LogLevel.Debug, - eventId: new EventId(0, "FailedToReadStackTraceInfo"), - formatString: "Failed to read stack trace information for exception."); - } - - public static void FailedToReadStackTraceInfo(this ILogger logger, Exception exception) - { - _failedToReadStackFrameInfo(logger, exception); - } + [LoggerMessage(EventId = 0, EventName = "FailedToReadStackTraceInfo", Level = LogLevel.Debug, Message = "Failed to read stack trace information for exception.")] + public static partial void FailedToReadStackTraceInfo(this ILogger logger, Exception exception); } } diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/Constants.cs b/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/Constants.cs index f6270c107d8e..a02f164d8eb9 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/Constants.cs +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/Constants.cs @@ -11,18 +11,11 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal { internal static class Constants { -#pragma warning disable CA1802 - public static readonly string UserAgent = "User-Agent"; -#pragma warning restore CA1802 - public static readonly string UserAgentHeader; + public static readonly string UserAgent = OperatingSystem.IsBrowser() ? "X-SignalR-User-Agent" : "User-Agent"; + public static readonly string UserAgentHeader = GetUserAgentHeader(); - static Constants() + private static string GetUserAgentHeader() { - if (OperatingSystem.IsBrowser()) - { - UserAgent = "X-SignalR-User-Agent"; - } - var assemblyVersion = typeof(Constants) .Assembly .GetCustomAttributes() @@ -33,7 +26,7 @@ static Constants() var runtime = ".NET"; var runtimeVersion = RuntimeInformation.FrameworkDescription; - UserAgentHeader = ConstructUserAgent(typeof(Constants).Assembly.GetName().Version!, assemblyVersion.InformationalVersion, GetOS(), runtime, runtimeVersion); + return ConstructUserAgent(typeof(Constants).Assembly.GetName().Version!, assemblyVersion.InformationalVersion, GetOS(), runtime, runtimeVersion); } private static string GetOS() diff --git a/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs b/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs index 22c3e0c918f9..284b516e7983 100644 --- a/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs +++ b/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs @@ -94,18 +94,20 @@ internal class SignalRResolver : IFormatterResolver private static class Cache { - public static readonly IMessagePackFormatter? Formatter; + public static readonly IMessagePackFormatter? Formatter = ResolveFormatter(); - static Cache() + private static IMessagePackFormatter? ResolveFormatter() { foreach (var resolver in Resolvers) { - Formatter = resolver.GetFormatter(); - if (Formatter != null) + var formatter = resolver.GetFormatter(); + if (formatter != null) { - return; + return formatter; } } + + return null; } } } diff --git a/src/SignalR/common/SignalR.Common/src/Protocol/HandshakeProtocol.cs b/src/SignalR/common/SignalR.Common/src/Protocol/HandshakeProtocol.cs index 10405f85dc3f..8e8ff0c617b7 100644 --- a/src/SignalR/common/SignalR.Common/src/Protocol/HandshakeProtocol.cs +++ b/src/SignalR/common/SignalR.Common/src/Protocol/HandshakeProtocol.cs @@ -3,7 +3,6 @@ using System; using System.Buffers; -using System.Collections.Concurrent; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; @@ -19,23 +18,22 @@ namespace Microsoft.AspNetCore.SignalR.Protocol public static class HandshakeProtocol { private const string ProtocolPropertyName = "protocol"; - private static JsonEncodedText ProtocolPropertyNameBytes = JsonEncodedText.Encode(ProtocolPropertyName); + private static readonly JsonEncodedText ProtocolPropertyNameBytes = JsonEncodedText.Encode(ProtocolPropertyName); private const string ProtocolVersionPropertyName = "version"; - private static JsonEncodedText ProtocolVersionPropertyNameBytes = JsonEncodedText.Encode(ProtocolVersionPropertyName); + private static readonly JsonEncodedText ProtocolVersionPropertyNameBytes = JsonEncodedText.Encode(ProtocolVersionPropertyName); private const string ErrorPropertyName = "error"; - private static JsonEncodedText ErrorPropertyNameBytes = JsonEncodedText.Encode(ErrorPropertyName); + private static readonly JsonEncodedText ErrorPropertyNameBytes = JsonEncodedText.Encode(ErrorPropertyName); private const string TypePropertyName = "type"; - private static JsonEncodedText TypePropertyNameBytes = JsonEncodedText.Encode(TypePropertyName); + private static readonly JsonEncodedText TypePropertyNameBytes = JsonEncodedText.Encode(TypePropertyName); + private static readonly ReadOnlyMemory _successHandshakeData = GetSuccessHandshakeData(); - private static readonly ReadOnlyMemory _successHandshakeData; - - static HandshakeProtocol() + private static ReadOnlyMemory GetSuccessHandshakeData() { var memoryBufferWriter = MemoryBufferWriter.Get(); try { WriteResponseMessage(HandshakeResponseMessage.Empty, memoryBufferWriter); - _successHandshakeData = memoryBufferWriter.ToArray(); + return memoryBufferWriter.ToArray(); } finally {