Skip to content

Commit 92975b3

Browse files
authored
Use LoggerMessage in HttpAbstractions (#33927)
* Use LoggerMessage in HttpAbstractions
1 parent 4cdd594 commit 92975b3

40 files changed

+412
-631
lines changed

src/Hosting/Hosting/src/GenericHost/GenericWebHostedService.cs

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Collections.Generic;
66
using System.Diagnostics;
77
using System.Linq;
8+
using System.Reflection;
89
using System.Threading;
910
using System.Threading.Tasks;
1011
using Microsoft.AspNetCore.Hosting.Builder;
@@ -18,18 +19,19 @@
1819

1920
namespace Microsoft.AspNetCore.Hosting
2021
{
21-
internal class GenericWebHostService : IHostedService
22+
internal sealed partial class GenericWebHostService : IHostedService
2223
{
23-
public GenericWebHostService(IOptions<GenericWebHostServiceOptions> options,
24-
IServer server,
25-
ILoggerFactory loggerFactory,
26-
DiagnosticListener diagnosticListener,
27-
ActivitySource activitySource,
28-
IHttpContextFactory httpContextFactory,
29-
IApplicationBuilderFactory applicationBuilderFactory,
30-
IEnumerable<IStartupFilter> startupFilters,
31-
IConfiguration configuration,
32-
IWebHostEnvironment hostingEnvironment)
24+
public GenericWebHostService(
25+
IOptions<GenericWebHostServiceOptions> options,
26+
IServer server,
27+
ILoggerFactory loggerFactory,
28+
DiagnosticListener diagnosticListener,
29+
ActivitySource activitySource,
30+
IHttpContextFactory httpContextFactory,
31+
IApplicationBuilderFactory applicationBuilderFactory,
32+
IEnumerable<IStartupFilter> startupFilters,
33+
IConfiguration configuration,
34+
IWebHostEnvironment hostingEnvironment)
3335
{
3436
Options = options.Value;
3537
Server = server;
@@ -122,15 +124,15 @@ public async Task StartAsync(CancellationToken cancellationToken)
122124
{
123125
foreach (var address in addresses)
124126
{
125-
LifetimeLogger.ListeningOnAddress(address);
127+
Log.ListeningOnAddress(LifetimeLogger, address);
126128
}
127129
}
128130

129131
if (Logger.IsEnabled(LogLevel.Debug))
130132
{
131133
foreach (var assembly in Options.WebHostOptions.GetFinalHostingStartupAssemblies())
132134
{
133-
Logger.StartupAssemblyLoaded(assembly);
135+
Log.StartupAssemblyLoaded(Logger, assembly);
134136
}
135137
}
136138

@@ -154,5 +156,19 @@ public async Task StopAsync(CancellationToken cancellationToken)
154156
HostingEventSource.Log.HostStop();
155157
}
156158
}
159+
160+
private static partial class Log
161+
{
162+
[LoggerMessage(14, LogLevel.Information,
163+
"Now listening on: {address}",
164+
EventName = "ListeningOnAddress")]
165+
public static partial void ListeningOnAddress(ILogger logger, string address);
166+
167+
[LoggerMessage(13, LogLevel.Debug,
168+
"Loaded hosting startup assembly {assemblyName}",
169+
EventName = "HostingStartupAssemblyLoaded",
170+
SkipEnabledCheck = true)]
171+
public static partial void StartupAssemblyLoaded(ILogger logger, string assemblyName);
172+
}
157173
}
158174
}

src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
5+
using System.Collections;
6+
using System.Collections.Generic;
57
using System.Diagnostics;
8+
using System.Globalization;
69
using System.Runtime.CompilerServices;
710
using System.Web;
811
using Microsoft.AspNetCore.Http;
@@ -87,7 +90,7 @@ public void BeginRequest(HttpContext httpContext, HostingApplication.Context con
8790
// Scope may be relevant for a different level of logging, so we always create it
8891
// see: https://github.com/aspnet/Hosting/pull/944
8992
// Scope can be null if logging is not on.
90-
context.Scope = _logger.RequestScope(httpContext);
93+
context.Scope = Log.RequestScope(_logger, httpContext);
9194

9295
if (_logger.IsEnabled(LogLevel.Information))
9396
{
@@ -359,5 +362,75 @@ private void StopActivity(Activity activity, HttpContext httpContext)
359362
_diagnosticListener.Write(ActivityStopKey, httpContext);
360363
activity.Stop(); // Resets Activity.Current (we want this after the Write)
361364
}
365+
366+
private static class Log
367+
{
368+
public static IDisposable RequestScope(ILogger logger, HttpContext httpContext)
369+
{
370+
return logger.BeginScope(new HostingLogScope(httpContext));
371+
}
372+
373+
private sealed class HostingLogScope : IReadOnlyList<KeyValuePair<string, object>>
374+
{
375+
private readonly string _path;
376+
private readonly string _traceIdentifier;
377+
378+
private string? _cachedToString;
379+
380+
public int Count => 2;
381+
382+
public KeyValuePair<string, object> this[int index]
383+
{
384+
get
385+
{
386+
if (index == 0)
387+
{
388+
return new KeyValuePair<string, object>("RequestId", _traceIdentifier);
389+
}
390+
else if (index == 1)
391+
{
392+
return new KeyValuePair<string, object>("RequestPath", _path);
393+
}
394+
395+
throw new ArgumentOutOfRangeException(nameof(index));
396+
}
397+
}
398+
399+
public HostingLogScope(HttpContext httpContext)
400+
{
401+
_traceIdentifier = httpContext.TraceIdentifier;
402+
_path = (httpContext.Request.PathBase.HasValue
403+
? httpContext.Request.PathBase + httpContext.Request.Path
404+
: httpContext.Request.Path).ToString();
405+
}
406+
407+
public override string ToString()
408+
{
409+
if (_cachedToString == null)
410+
{
411+
_cachedToString = string.Format(
412+
CultureInfo.InvariantCulture,
413+
"RequestPath:{0} RequestId:{1}",
414+
_path,
415+
_traceIdentifier);
416+
}
417+
418+
return _cachedToString;
419+
}
420+
421+
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
422+
{
423+
for (var i = 0; i < Count; ++i)
424+
{
425+
yield return this[i];
426+
}
427+
}
428+
429+
IEnumerator IEnumerable.GetEnumerator()
430+
{
431+
return GetEnumerator();
432+
}
433+
}
434+
}
362435
}
363436
}

src/Hosting/Hosting/src/Internal/HostingLoggerExtensions.cs

Lines changed: 1 addition & 136 deletions
Original file line numberDiff line numberDiff line change
@@ -2,38 +2,13 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
5-
using System.Collections;
6-
using System.Collections.Generic;
7-
using System.Globalization;
85
using System.Reflection;
9-
using Microsoft.AspNetCore.Http;
106
using Microsoft.Extensions.Logging;
117

128
namespace Microsoft.AspNetCore.Hosting
139
{
1410
internal static class HostingLoggerExtensions
1511
{
16-
private static readonly Action<ILogger, string, Exception?> _startupAssemblyLoaded =
17-
LoggerMessage.Define<string>(LogLevel.Debug, LoggerEventIds.HostingStartupAssemblyLoaded, "Loaded hosting startup assembly {assemblyName}", skipEnabledCheck: true);
18-
19-
private static readonly Action<ILogger, string, Exception?> _listeningOnAddress =
20-
LoggerMessage.Define<string>(LogLevel.Information, LoggerEventIds.ServerListeningOnAddresses, "Now listening on: {address}");
21-
22-
public static IDisposable RequestScope(this ILogger logger, HttpContext httpContext)
23-
{
24-
return logger.BeginScope(new HostingLogScope(httpContext));
25-
}
26-
27-
public static void ListeningOnAddress(this ILogger logger, string address)
28-
{
29-
_listeningOnAddress(logger, address, null);
30-
}
31-
32-
public static void StartupAssemblyLoaded(this ILogger logger, string assemblyName)
33-
{
34-
_startupAssemblyLoaded(logger, assemblyName, null);
35-
}
36-
3712
public static void ApplicationError(this ILogger logger, Exception exception)
3813
{
3914
logger.ApplicationError(
@@ -52,8 +27,7 @@ public static void HostingStartupAssemblyError(this ILogger logger, Exception ex
5227

5328
public static void ApplicationError(this ILogger logger, EventId eventId, string message, Exception exception)
5429
{
55-
var reflectionTypeLoadException = exception as ReflectionTypeLoadException;
56-
if (reflectionTypeLoadException != null)
30+
if (exception is ReflectionTypeLoadException reflectionTypeLoadException)
5731
{
5832
foreach (var ex in reflectionTypeLoadException.LoaderExceptions)
5933
{
@@ -69,115 +43,6 @@ public static void ApplicationError(this ILogger logger, EventId eventId, string
6943
message: message,
7044
exception: exception);
7145
}
72-
73-
public static void Starting(this ILogger logger)
74-
{
75-
if (logger.IsEnabled(LogLevel.Debug))
76-
{
77-
logger.LogDebug(
78-
eventId: LoggerEventIds.Starting,
79-
message: "Hosting starting");
80-
}
81-
}
82-
83-
public static void Started(this ILogger logger)
84-
{
85-
if (logger.IsEnabled(LogLevel.Debug))
86-
{
87-
logger.LogDebug(
88-
eventId: LoggerEventIds.Started,
89-
message: "Hosting started");
90-
}
91-
}
92-
93-
public static void Shutdown(this ILogger logger)
94-
{
95-
if (logger.IsEnabled(LogLevel.Debug))
96-
{
97-
logger.LogDebug(
98-
eventId: LoggerEventIds.Shutdown,
99-
message: "Hosting shutdown");
100-
}
101-
}
102-
103-
public static void ServerShutdownException(this ILogger logger, Exception ex)
104-
{
105-
if (logger.IsEnabled(LogLevel.Debug))
106-
{
107-
logger.LogDebug(
108-
eventId: LoggerEventIds.ServerShutdownException,
109-
exception: ex,
110-
message: "Server shutdown exception");
111-
}
112-
}
113-
114-
private class HostingLogScope : IReadOnlyList<KeyValuePair<string, object>>
115-
{
116-
private readonly string _path;
117-
private readonly string _traceIdentifier;
118-
119-
private string? _cachedToString;
120-
121-
public int Count
122-
{
123-
get
124-
{
125-
return 2;
126-
}
127-
}
128-
129-
public KeyValuePair<string, object> this[int index]
130-
{
131-
get
132-
{
133-
if (index == 0)
134-
{
135-
return new KeyValuePair<string, object>("RequestId", _traceIdentifier);
136-
}
137-
else if (index == 1)
138-
{
139-
return new KeyValuePair<string, object>("RequestPath", _path);
140-
}
141-
142-
throw new ArgumentOutOfRangeException(nameof(index));
143-
}
144-
}
145-
146-
public HostingLogScope(HttpContext httpContext)
147-
{
148-
_traceIdentifier = httpContext.TraceIdentifier;
149-
_path = (httpContext.Request.PathBase.HasValue
150-
? httpContext.Request.PathBase + httpContext.Request.Path
151-
: httpContext.Request.Path).ToString();
152-
}
153-
154-
public override string ToString()
155-
{
156-
if (_cachedToString == null)
157-
{
158-
_cachedToString = string.Format(
159-
CultureInfo.InvariantCulture,
160-
"RequestPath:{0} RequestId:{1}",
161-
_path,
162-
_traceIdentifier);
163-
}
164-
165-
return _cachedToString;
166-
}
167-
168-
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
169-
{
170-
for (int i = 0; i < Count; ++i)
171-
{
172-
yield return this[i];
173-
}
174-
}
175-
176-
IEnumerator IEnumerable.GetEnumerator()
177-
{
178-
return GetEnumerator();
179-
}
180-
}
18146
}
18247
}
18348

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
11
// Copyright (c) .NET Foundation. All rights reserved.
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3-
using Microsoft.Extensions.Logging;
43

54
namespace Microsoft.AspNetCore.Hosting
65
{
76
internal static class LoggerEventIds
87
{
9-
public static readonly EventId RequestStarting = new EventId(1, "RequestStarting");
10-
public static readonly EventId RequestFinished = new EventId(2, "RequestFinished");
11-
public static readonly EventId Starting = new EventId(3, "Starting");
12-
public static readonly EventId Started = new EventId(4, "Started");
13-
public static readonly EventId Shutdown = new EventId(5, "Shutdown");
14-
public static readonly EventId ApplicationStartupException = new EventId(6, "ApplicationStartupException");
15-
public static readonly EventId ApplicationStoppingException = new EventId(7, "ApplicationStoppingException");
16-
public static readonly EventId ApplicationStoppedException = new EventId(8, "ApplicationStoppedException");
17-
public static readonly EventId HostedServiceStartException = new EventId(9, "HostedServiceStartException");
18-
public static readonly EventId HostedServiceStopException = new EventId(10, "HostedServiceStopException");
19-
public static readonly EventId HostingStartupAssemblyException = new EventId(11, "HostingStartupAssemblyException");
20-
public static readonly EventId ServerShutdownException = new EventId(12, "ServerShutdownException");
21-
public static readonly EventId HostingStartupAssemblyLoaded = new EventId(13, "HostingStartupAssemblyLoaded");
22-
public static readonly EventId ServerListeningOnAddresses = new EventId(14, "ServerListeningOnAddresses");
8+
public const int RequestStarting = 1;
9+
public const int RequestFinished = 2;
10+
public const int Starting = 3;
11+
public const int Started = 4;
12+
public const int Shutdown = 5;
13+
public const int ApplicationStartupException = 6;
14+
public const int ApplicationStoppingException = 7;
15+
public const int ApplicationStoppedException = 8;
16+
public const int HostedServiceStartException = 9;
17+
public const int HostedServiceStopException = 10;
18+
public const int HostingStartupAssemblyException = 11;
19+
public const int ServerShutdownException = 12;
20+
public const int HostingStartupAssemblyLoaded = 13;
21+
public const int ServerListeningOnAddresses = 14;
2322
}
2423
}

0 commit comments

Comments
 (0)