diff --git a/src/Microsoft.AspNetCore.Hosting/Internal/HostingApplication.cs b/src/Microsoft.AspNetCore.Hosting/Internal/HostingApplication.cs index 5f95916e..1e88d807 100644 --- a/src/Microsoft.AspNetCore.Hosting/Internal/HostingApplication.cs +++ b/src/Microsoft.AspNetCore.Hosting/Internal/HostingApplication.cs @@ -52,7 +52,7 @@ public Context CreateContext(IFeatureCollection contextFeatures) return new Context { HttpContext = httpContext, - Scope = scope, + Scope = scope, // Scope can be null if logging is not on. StartTimestamp = startTimestamp, }; } diff --git a/src/Microsoft.AspNetCore.Hosting/Internal/HostingLoggerExtensions.cs b/src/Microsoft.AspNetCore.Hosting/Internal/HostingLoggerExtensions.cs index 35072a39..2ee490df 100644 --- a/src/Microsoft.AspNetCore.Hosting/Internal/HostingLoggerExtensions.cs +++ b/src/Microsoft.AspNetCore.Hosting/Internal/HostingLoggerExtensions.cs @@ -18,7 +18,11 @@ internal static class HostingLoggerExtensions public static IDisposable RequestScope(this ILogger logger, HttpContext httpContext) { - return logger.BeginScope(new HostingLogScope(httpContext)); + // to avoid allocation, return a null scope if the logger is not on at least to some degree. + if (logger.IsEnabled(LogLevel.Critical)) + return logger.BeginScope(new HostingLogScope(httpContext)); + else + return null; } public static void RequestStarting(this ILogger logger, HttpContext httpContext)