From 8165609f4e403eae530ca435b1de3258baf3dc4c Mon Sep 17 00:00:00 2001 From: Vance Morrison Date: Tue, 28 Mar 2017 11:43:58 -0700 Subject: [PATCH] Logging optimization.2 14 (#944) * Trivial change to avoid an allocation when logging is off (normal case). --- .../Internal/HostingApplication.cs | 2 +- .../Internal/HostingLoggerExtensions.cs | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.AspNetCore.Hosting/Internal/HostingApplication.cs b/src/Microsoft.AspNetCore.Hosting/Internal/HostingApplication.cs index c44d58d5e6..408f43cb6a 100644 --- a/src/Microsoft.AspNetCore.Hosting/Internal/HostingApplication.cs +++ b/src/Microsoft.AspNetCore.Hosting/Internal/HostingApplication.cs @@ -75,7 +75,7 @@ namespace Microsoft.AspNetCore.Hosting.Internal 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 ddec1ab7d8..e25f448331 100644 --- a/src/Microsoft.AspNetCore.Hosting/Internal/HostingLoggerExtensions.cs +++ b/src/Microsoft.AspNetCore.Hosting/Internal/HostingLoggerExtensions.cs @@ -15,7 +15,11 @@ namespace Microsoft.AspNetCore.Hosting.Internal { 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 ApplicationError(this ILogger logger, Exception exception)