Skip to content

Commit 020745c

Browse files
Use LoggerMessage.Define in HttpSys (#31333)
- Use LoggerMessage.Define() throughout HttpSys instead of ILogger extension methods. - Also updates two incorrect event Id field names. Fixes #31313.
1 parent 223541c commit 020745c

21 files changed

+534
-64
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
using System;
5+
using Microsoft.Extensions.Logging;
6+
7+
namespace Microsoft.AspNetCore.Server.HttpSys
8+
{
9+
internal partial class HttpSysListener
10+
{
11+
private static class Log
12+
{
13+
private static readonly Action<ILogger, Exception?> _listenerDisposeError =
14+
LoggerMessage.Define(LogLevel.Error, LoggerEventIds.ListenerDisposeError, "Dispose");
15+
16+
private static readonly Action<ILogger, Exception?> _listenerDisposing =
17+
LoggerMessage.Define(LogLevel.Trace, LoggerEventIds.ListenerDisposing, "Disposing the listener.");
18+
19+
private static readonly Action<ILogger, Exception?> _httpSysListenerCtorError =
20+
LoggerMessage.Define(LogLevel.Error, LoggerEventIds.HttpSysListenerCtorError, ".Ctor");
21+
22+
private static readonly Action<ILogger, Exception?> _listenerStartError =
23+
LoggerMessage.Define(LogLevel.Error, LoggerEventIds.ListenerStartError, "Start");
24+
25+
private static readonly Action<ILogger, Exception?> _listenerStarting =
26+
LoggerMessage.Define(LogLevel.Trace, LoggerEventIds.ListenerStarting, "Starting the listener.");
27+
28+
private static readonly Action<ILogger, Exception?> _listenerStopError =
29+
LoggerMessage.Define(LogLevel.Error, LoggerEventIds.ListenerStopError, "Stop");
30+
31+
private static readonly Action<ILogger, Exception?> _listenerStopping =
32+
LoggerMessage.Define(LogLevel.Trace, LoggerEventIds.ListenerStopping, "Stopping the listener.");
33+
34+
private static readonly Action<ILogger, ulong, Exception?> _requestValidationFailed =
35+
LoggerMessage.Define<ulong>(LogLevel.Error, LoggerEventIds.RequestValidationFailed, "Error validating request {RequestId}");
36+
37+
public static void ListenerDisposeError(ILogger logger, Exception exception)
38+
{
39+
_listenerDisposeError(logger, exception);
40+
}
41+
42+
public static void ListenerDisposing(ILogger logger)
43+
{
44+
_listenerDisposing(logger, null);
45+
}
46+
47+
public static void HttpSysListenerCtorError(ILogger logger, Exception exception)
48+
{
49+
_httpSysListenerCtorError(logger, exception);
50+
}
51+
52+
public static void ListenerStartError(ILogger logger, Exception exception)
53+
{
54+
_listenerStartError(logger, exception);
55+
}
56+
57+
public static void ListenerStarting(ILogger logger)
58+
{
59+
_listenerStarting(logger, null);
60+
}
61+
62+
public static void ListenerStopError(ILogger logger, Exception exception)
63+
{
64+
_listenerStopError(logger, exception);
65+
}
66+
67+
public static void ListenerStopping(ILogger logger)
68+
{
69+
_listenerStopping(logger, null);
70+
}
71+
72+
public static void RequestValidationFailed(ILogger logger, Exception exception, ulong requestId)
73+
{
74+
_requestValidationFailed(logger, requestId, exception);
75+
}
76+
}
77+
}
78+
}

src/Servers/HttpSys/src/HttpSysListener.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys
1616
/// <summary>
1717
/// An HTTP server wrapping the Http.Sys APIs that accepts requests.
1818
/// </summary>
19-
internal class HttpSysListener : IDisposable
19+
internal partial class HttpSysListener : IDisposable
2020
{
2121
// Win8# 559317 fixed a bug in Http.sys's HttpReceiveClientCertificate method.
2222
// Without this fix IOCP callbacks were not being called although ERROR_IO_PENDING was
@@ -92,7 +92,7 @@ public HttpSysListener(HttpSysOptions options, ILoggerFactory loggerFactory)
9292
_requestQueue?.Dispose();
9393
_urlGroup?.Dispose();
9494
_serverSession?.Dispose();
95-
Logger.LogError(LoggerEventIds.HttpSysListenerCtorError, exception, ".Ctor");
95+
Log.HttpSysListenerCtorError(Logger, exception);
9696
throw;
9797
}
9898
}
@@ -135,7 +135,7 @@ public void Start()
135135
{
136136
CheckDisposed();
137137

138-
Logger.LogTrace(LoggerEventIds.ListenerStarting, "Starting the listener.");
138+
Log.ListenerStarting(Logger);
139139

140140
// Make sure there are no race conditions between Start/Stop/Abort/Close/Dispose.
141141
// Start needs to setup all resources. Abort/Stop must not interfere while Start is
@@ -177,7 +177,7 @@ public void Start()
177177
// Make sure the HttpListener instance can't be used if Start() failed.
178178
_state = State.Disposed;
179179
DisposeInternal();
180-
Logger.LogError(LoggerEventIds.ListenerStartError, exception, "Start");
180+
Log.ListenerStartError(Logger, exception);
181181
throw;
182182
}
183183
}
@@ -195,7 +195,7 @@ private void Stop()
195195
return;
196196
}
197197

198-
Logger.LogTrace(LoggerEventIds.ListenerStopping, "Stopping the listener.");
198+
Log.ListenerStopping(Logger);
199199

200200
// If this instance created the queue then remove the URL prefixes before shutting down.
201201
if (_requestQueue.Created)
@@ -210,7 +210,7 @@ private void Stop()
210210
}
211211
catch (Exception exception)
212212
{
213-
Logger.LogError(LoggerEventIds.ListenerStopError, exception, "Stop");
213+
Log.ListenerStopError(Logger, exception);
214214
throw;
215215
}
216216
}
@@ -238,14 +238,14 @@ private void Dispose(bool disposing)
238238
{
239239
return;
240240
}
241-
Logger.LogTrace(LoggerEventIds.ListenerDisposing, "Disposing the listener.");
241+
Log.ListenerDisposing(Logger);
242242

243243
Stop();
244244
DisposeInternal();
245245
}
246246
catch (Exception exception)
247247
{
248-
Logger.LogError(LoggerEventIds.ListenerDisposeError, exception, "Dispose");
248+
Log.ListenerDisposeError(Logger, exception);
249249
throw;
250250
}
251251
finally
@@ -305,7 +305,7 @@ internal bool ValidateRequest(NativeRequestContext requestMemory)
305305
}
306306
catch (Exception ex)
307307
{
308-
Logger.LogError(LoggerEventIds.RequestValidationFailed, ex, "Error validating request {RequestId}", requestMemory.RequestId);
308+
Log.RequestValidationFailed(Logger, ex, requestMemory.RequestId);
309309
return false;
310310
}
311311

src/Servers/HttpSys/src/LoggerEventIds.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,12 @@ internal static class LoggerEventIds
2525
public static EventId RegisteringPrefix = new EventId(19, "RegisteringPrefix");
2626
public static EventId UnregisteringPrefix = new EventId(20, "UnregisteringPrefix");
2727
public static EventId CloseUrlGroupError = new EventId(21, "CloseUrlGroupError");
28-
public static EventId ChannelBindingUnSupported = new EventId(22, "ChannelBindingUnSupported");
28+
public static EventId ChannelBindingUnsupported = new EventId(22, "ChannelBindingUnSupported");
2929
public static EventId ChannelBindingMissing = new EventId(23, "ChannelBindingMissing");
3030
public static EventId RequestError = new EventId(24, "RequestError");
3131
public static EventId ErrorInReadingCertificate = new EventId(25, "ErrorInReadingCertificate");
3232
public static EventId ChannelBindingNeedsHttps = new EventId(26, "ChannelBindingNeedsHttps");
33-
public static EventId ChannelBindingRetrived = new EventId(27, "ChannelBindingRetrived");
33+
public static EventId ChannelBindingRetrieved = new EventId(27, "ChannelBindingRetrived");
3434
public static EventId AbortError = new EventId(28, "AbortError");
3535
public static EventId ErrorWhileRead = new EventId(29, "ErrorWhileRead");
3636
public static EventId ErrorWhenReadBegun = new EventId(30, "ErrorWhenReadBegun");
@@ -51,5 +51,6 @@ internal static class LoggerEventIds
5151
public static EventId ListenerStopError = new EventId(45, "ListenerStopError");
5252
public static EventId ListenerDisposing = new EventId(46, "ListenerDisposing");
5353
public static EventId RequestValidationFailed = new EventId(47, "RequestValidationFailed");
54+
public static EventId CreateDisconnectTokenError = new EventId(48, "CreateDisconnectTokenError");
5455
}
5556
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
using System;
5+
using System.Collections.Generic;
6+
using Microsoft.AspNetCore.Hosting.Server.Features;
7+
using Microsoft.AspNetCore.HttpSys.Internal;
8+
using Microsoft.Extensions.Logging;
9+
10+
namespace Microsoft.AspNetCore.Server.HttpSys
11+
{
12+
internal partial class MessagePump
13+
{
14+
private static class Log
15+
{
16+
private static readonly Action<ILogger, Exception?> _acceptError =
17+
LoggerMessage.Define(LogLevel.Error, LoggerEventIds.AcceptError, "Failed to accept a request.");
18+
19+
private static readonly Action<ILogger, Exception?> _acceptErrorStopping =
20+
LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.AcceptErrorStopping, "Failed to accept a request, the server is stopping.");
21+
22+
private static readonly Action<ILogger, Exception?> _bindingToDefault =
23+
LoggerMessage.Define(LogLevel.Debug, LoggerEventIds.BindingToDefault, $"No listening endpoints were configured. Binding to {Constants.DefaultServerAddress} by default.");
24+
25+
private static readonly Action<ILogger, string, Exception?> _clearedAddresses =
26+
LoggerMessage.Define<string>(LogLevel.Warning, LoggerEventIds.ClearedAddresses, $"Overriding address(es) '{{ServerAddresses)}}'. Binding to endpoints added to {nameof(HttpSysOptions.UrlPrefixes)} instead.");
27+
28+
private static readonly Action<ILogger, string, Exception?> _clearedPrefixes =
29+
LoggerMessage.Define<string>(LogLevel.Warning, LoggerEventIds.ClearedPrefixes, $"Overriding endpoints added to {nameof(HttpSysOptions.UrlPrefixes)} since {nameof(IServerAddressesFeature.PreferHostingUrls)} is set to true. Binding to address(es) '{{ServerAddresses}}' instead. ");
30+
31+
private static readonly Action<ILogger, Exception?> _requestListenerProcessError =
32+
LoggerMessage.Define(LogLevel.Error, LoggerEventIds.RequestListenerProcessError, "ProcessRequestAsync");
33+
34+
private static readonly Action<ILogger, int, Exception?> _stopCancelled =
35+
LoggerMessage.Define<int>(LogLevel.Information, LoggerEventIds.StopCancelled, "Canceled, terminating {OutstandingRequests} request(s).");
36+
37+
private static readonly Action<ILogger, int, Exception?> _waitingForRequestsToDrain =
38+
LoggerMessage.Define<int>(LogLevel.Information, LoggerEventIds.WaitingForRequestsToDrain, "Stopping, waiting for {OutstandingRequests} request(s) to drain.");
39+
40+
public static void AcceptError(ILogger logger, Exception exception)
41+
{
42+
_acceptError(logger, exception);
43+
}
44+
45+
public static void AcceptErrorStopping(ILogger logger, Exception exception)
46+
{
47+
_acceptErrorStopping(logger, exception);
48+
}
49+
50+
public static void BindingToDefault(ILogger logger)
51+
{
52+
_bindingToDefault(logger, null);
53+
}
54+
55+
public static void ClearedAddresses(ILogger logger, ICollection<string> serverAddresses)
56+
{
57+
if (logger.IsEnabled(LogLevel.Warning))
58+
{
59+
_clearedAddresses(logger, string.Join(", ", serverAddresses), null);
60+
}
61+
}
62+
63+
public static void ClearedPrefixes(ILogger logger, ICollection<string> serverAddresses)
64+
{
65+
if (logger.IsEnabled(LogLevel.Warning))
66+
{
67+
_clearedPrefixes(logger, string.Join(", ", serverAddresses), null);
68+
}
69+
}
70+
71+
public static void RequestListenerProcessError(ILogger logger, Exception exception)
72+
{
73+
_requestListenerProcessError(logger, exception);
74+
}
75+
76+
public static void StopCancelled(ILogger logger, int outstandingRequests)
77+
{
78+
_stopCancelled(logger, outstandingRequests, null);
79+
}
80+
81+
public static void WaitingForRequestsToDrain(ILogger logger, int outstandingRequests)
82+
{
83+
_waitingForRequestsToDrain(logger, outstandingRequests, null);
84+
}
85+
}
86+
}
87+
}

src/Servers/HttpSys/src/MessagePump.cs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
namespace Microsoft.AspNetCore.Server.HttpSys
1919
{
20-
internal class MessagePump : IServer
20+
internal partial class MessagePump : IServer
2121
{
2222
private readonly ILogger _logger;
2323
private readonly HttpSysOptions _options;
@@ -87,8 +87,7 @@ public Task StartAsync<TContext>(IHttpApplication<TContext> application, Cancell
8787
{
8888
if (_options.UrlPrefixes.Count > 0)
8989
{
90-
_logger.LogWarning(LoggerEventIds.ClearedPrefixes, $"Overriding endpoints added to {nameof(HttpSysOptions.UrlPrefixes)} since {nameof(IServerAddressesFeature.PreferHostingUrls)} is set to true." +
91-
$" Binding to address(es) '{string.Join(", ", _serverAddresses.Addresses)}' instead. ");
90+
Log.ClearedPrefixes(_logger, _serverAddresses.Addresses);
9291

9392
Listener.Options.UrlPrefixes.Clear();
9493
}
@@ -99,20 +98,18 @@ public Task StartAsync<TContext>(IHttpApplication<TContext> application, Cancell
9998
{
10099
if (hostingUrlsPresent)
101100
{
102-
_logger.LogWarning(LoggerEventIds.ClearedAddresses, $"Overriding address(es) '{string.Join(", ", _serverAddresses.Addresses)}'. " +
103-
$"Binding to endpoints added to {nameof(HttpSysOptions.UrlPrefixes)} instead.");
101+
Log.ClearedAddresses(_logger, _serverAddresses.Addresses);
104102

105103
_serverAddresses.Addresses.Clear();
106104
}
107-
108105
}
109106
else if (hostingUrlsPresent)
110107
{
111108
UpdateUrlPrefixes(serverAddressCopy);
112109
}
113110
else if (Listener.RequestQueue.Created)
114111
{
115-
_logger.LogDebug(LoggerEventIds.BindingToDefault, $"No listening endpoints were configured. Binding to {Constants.DefaultServerAddress} by default.");
112+
Log.BindingToDefault(_logger);
116113

117114
Listener.Options.UrlPrefixes.Add(Constants.DefaultServerAddress);
118115
}
@@ -207,11 +204,11 @@ private async Task ProcessRequestsWorker()
207204
Debug.Assert(Stopping);
208205
if (Stopping)
209206
{
210-
_logger.LogDebug(LoggerEventIds.AcceptErrorStopping, exception, "Failed to accept a request, the server is stopping.");
207+
Log.AcceptErrorStopping(_logger, exception);
211208
}
212209
else
213210
{
214-
_logger.LogError(LoggerEventIds.AcceptError, exception, "Failed to accept a request.");
211+
Log.AcceptError(_logger, exception);
215212
}
216213
continue;
217214
}
@@ -223,7 +220,7 @@ private async Task ProcessRequestsWorker()
223220
{
224221
// Request processing failed to be queued in threadpool
225222
// Log the error message, release throttle and move on
226-
_logger.LogError(LoggerEventIds.RequestListenerProcessError, ex, "ProcessRequestAsync");
223+
Log.RequestListenerProcessError(_logger, ex);
227224
}
228225
}
229226
Interlocked.Decrement(ref _acceptorCounts);
@@ -237,7 +234,7 @@ void RegisterCancelation()
237234
{
238235
if (Interlocked.Exchange(ref _shutdownSignalCompleted, 1) == 0)
239236
{
240-
_logger.LogInformation(LoggerEventIds.StopCancelled, "Canceled, terminating " + _outstandingRequests + " request(s).");
237+
Log.StopCancelled(_logger, _outstandingRequests);
241238
_shutdownSignal.TrySetResult();
242239
}
243240
});
@@ -255,7 +252,7 @@ void RegisterCancelation()
255252
// Wait for active requests to drain
256253
if (_outstandingRequests > 0)
257254
{
258-
_logger.LogInformation(LoggerEventIds.WaitingForRequestsToDrain, "Stopping, waiting for " + _outstandingRequests + " request(s) to drain.");
255+
Log.WaitingForRequestsToDrain(_logger, _outstandingRequests);
259256
RegisterCancelation();
260257
}
261258
else

0 commit comments

Comments
 (0)