Skip to content

Commit 631bf68

Browse files
committed
Use LoggerMessage in HttpAbstractions
1 parent d679387 commit 631bf68

28 files changed

+259
-459
lines changed

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

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,28 +11,23 @@
1111

1212
namespace Microsoft.AspNetCore.Hosting
1313
{
14-
internal static class HostingLoggerExtensions
14+
internal static partial class HostingLoggerExtensions
1515
{
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-
2216
public static IDisposable RequestScope(this ILogger logger, HttpContext httpContext)
2317
{
2418
return logger.BeginScope(new HostingLogScope(httpContext));
2519
}
2620

27-
public static void ListeningOnAddress(this ILogger logger, string address)
28-
{
29-
_listeningOnAddress(logger, address, null);
30-
}
21+
[LoggerMessage(LoggerEventIds.ServerListeningOnAddresses, LogLevel.Information,
22+
"Now listening on: {address}",
23+
EventName = "ListeningOnAddress")]
24+
public static partial void ListeningOnAddress(this ILogger logger, string address);
3125

32-
public static void StartupAssemblyLoaded(this ILogger logger, string assemblyName)
33-
{
34-
_startupAssemblyLoaded(logger, assemblyName, null);
35-
}
26+
[LoggerMessage(LoggerEventIds.HostingStartupAssemblyLoaded, LogLevel.Debug,
27+
"Loaded hosting startup assembly {assemblyName}",
28+
EventName = "HostingStartupAssemblyLoaded",
29+
SkipEnabledCheck = true)]
30+
public static partial void StartupAssemblyLoaded(this ILogger logger, string assemblyName);
3631

3732
public static void ApplicationError(this ILogger logger, Exception exception)
3833
{
@@ -52,8 +47,7 @@ public static void HostingStartupAssemblyError(this ILogger logger, Exception ex
5247

5348
public static void ApplicationError(this ILogger logger, EventId eventId, string message, Exception exception)
5449
{
55-
var reflectionTypeLoadException = exception as ReflectionTypeLoadException;
56-
if (reflectionTypeLoadException != null)
50+
if (exception is ReflectionTypeLoadException reflectionTypeLoadException)
5751
{
5852
foreach (var ex in reflectionTypeLoadException.LoaderExceptions)
5953
{
@@ -167,7 +161,7 @@ public override string ToString()
167161

168162
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
169163
{
170-
for (int i = 0; i < Count; ++i)
164+
for (var i = 0; i < Count; ++i)
171165
{
172166
yield return this[i];
173167
}
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
}

src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Microsoft.AspNetCore.Http.HttpResponse</Description>
1919
<ItemGroup>
2020
<Reference Include="Microsoft.AspNetCore.Http.Features" />
2121
<Reference Include="Microsoft.Net.Http.Headers" />
22+
<Reference Include="Microsoft.Extensions.Logging.Abstractions" />
2223

2324
<Compile Include="$(SharedSourceRoot)ActivatorUtilities\*.cs" />
2425
<Compile Include="$(SharedSourceRoot)ParameterDefaultValue\*.cs" />

src/Http/Http.Extensions/src/RequestDelegateFactory.cs

Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Http
1919
/// <summary>
2020
/// Creates <see cref="RequestDelegate"/> implementations from <see cref="Delegate"/> request handlers.
2121
/// </summary>
22-
public static class RequestDelegateFactory
22+
public static partial class RequestDelegateFactory
2323
{
2424
private static readonly MethodInfo ExecuteTaskOfTMethod = typeof(RequestDelegateFactory).GetMethod(nameof(ExecuteTask), BindingFlags.NonPublic | BindingFlags.Static)!;
2525
private static readonly MethodInfo ExecuteTaskOfStringMethod = typeof(RequestDelegateFactory).GetMethod(nameof(ExecuteTaskOfString), BindingFlags.NonPublic | BindingFlags.Static)!;
@@ -734,37 +734,27 @@ private class FactoryContext
734734
public List<(ParameterExpression, Expression)> TryParseParams { get; } = new();
735735
}
736736

737-
private static class Log
737+
private static partial class Log
738738
{
739-
private static readonly Action<ILogger, Exception> _requestBodyIOException = LoggerMessage.Define(
740-
LogLevel.Debug,
741-
new EventId(1, "RequestBodyIOException"),
742-
"Reading the request body failed with an IOException.");
743-
744-
private static readonly Action<ILogger, Exception> _requestBodyInvalidDataException = LoggerMessage.Define(
745-
LogLevel.Debug,
746-
new EventId(2, "RequestBodyInvalidDataException"),
747-
"Reading the request body failed with an InvalidDataException.");
748-
749-
private static readonly Action<ILogger, string, string, string, Exception?> _parameterBindingFailed = LoggerMessage.Define<string, string, string>(
750-
LogLevel.Debug,
751-
new EventId(3, "ParamaterBindingFailed"),
752-
@"Failed to bind parameter ""{ParameterType} {ParameterName}"" from ""{SourceValue}"".");
753-
754739
public static void RequestBodyIOException(HttpContext httpContext, IOException exception)
755-
{
756-
_requestBodyIOException(GetLogger(httpContext), exception);
757-
}
740+
=> RequestBodyIOException(GetLogger(httpContext), exception);
741+
742+
[LoggerMessage(1, LogLevel.Debug, "Reading the request body failed with an IOException.", EventName = "RequestBodyIOException")]
743+
private static partial void RequestBodyIOException(ILogger logger, IOException exception);
758744

759745
public static void RequestBodyInvalidDataException(HttpContext httpContext, InvalidDataException exception)
760-
{
761-
_requestBodyInvalidDataException(GetLogger(httpContext), exception);
762-
}
746+
=> RequestBodyInvalidDataException(GetLogger(httpContext), exception);
747+
748+
[LoggerMessage(2, LogLevel.Debug, "Reading the request body failed with an InvalidDataException.", EventName = "RequestBodyInvalidDataException")]
749+
private static partial void RequestBodyInvalidDataException(ILogger logger, InvalidDataException exception);
763750

764751
public static void ParameterBindingFailed(HttpContext httpContext, string parameterTypeName, string parameterName, string sourceValue)
765-
{
766-
_parameterBindingFailed(GetLogger(httpContext), parameterTypeName, parameterName, sourceValue, null);
767-
}
752+
=> ParameterBindingFailed(GetLogger(httpContext), parameterTypeName, parameterName, sourceValue);
753+
754+
[LoggerMessage(3, LogLevel.Debug,
755+
@"Failed to bind parameter ""{ParameterType} {ParameterName}"" from ""{SourceValue}"".",
756+
EventName = "ParamaterBindingFailed")]
757+
private static partial void ParameterBindingFailed(ILogger logger, string parameterType, string parameterName, string sourceValue);
768758

769759
private static ILogger GetLogger(HttpContext httpContext)
770760
{

src/Http/Http/src/BindingAddress.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -129,12 +129,12 @@ public static BindingAddress Parse(string address)
129129
// A null/empty address will throw FormatException
130130
address = address ?? string.Empty;
131131

132-
int schemeDelimiterStart = address.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal);
132+
var schemeDelimiterStart = address.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal);
133133
if (schemeDelimiterStart < 0)
134134
{
135135
throw new FormatException($"Invalid url: '{address}'");
136136
}
137-
int schemeDelimiterEnd = schemeDelimiterStart + Uri.SchemeDelimiter.Length;
137+
var schemeDelimiterEnd = schemeDelimiterStart + Uri.SchemeDelimiter.Length;
138138

139139
var isUnixPipe = address.IndexOf(UnixPipeHostPrefix, schemeDelimiterEnd, StringComparison.Ordinal) == schemeDelimiterEnd;
140140

@@ -169,17 +169,17 @@ public static BindingAddress Parse(string address)
169169

170170
var scheme = address.Substring(0, schemeDelimiterStart);
171171
string? host = null;
172-
int port = 0;
172+
var port = 0;
173173

174174
var hasSpecifiedPort = false;
175175
if (!isUnixPipe)
176176
{
177-
int portDelimiterStart = address.LastIndexOf(":", pathDelimiterStart - 1, pathDelimiterStart - schemeDelimiterEnd, StringComparison.Ordinal);
177+
var portDelimiterStart = address.LastIndexOf(":", pathDelimiterStart - 1, pathDelimiterStart - schemeDelimiterEnd, StringComparison.Ordinal);
178178
if (portDelimiterStart >= 0)
179179
{
180-
int portDelimiterEnd = portDelimiterStart + ":".Length;
180+
var portDelimiterEnd = portDelimiterStart + ":".Length;
181181

182-
string portString = address.Substring(portDelimiterEnd, pathDelimiterStart - portDelimiterEnd);
182+
var portString = address.Substring(portDelimiterEnd, pathDelimiterStart - portDelimiterEnd);
183183
int portNumber;
184184
if (int.TryParse(portString, NumberStyles.Integer, CultureInfo.InvariantCulture, out portNumber))
185185
{

src/Http/Http/src/Features/HttpRequestIdentifierFeature.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ private static string GenerateRequestId(long id)
4242
{
4343
return string.Create(13, id, (buffer, value) =>
4444
{
45-
char[] encode32Chars = s_encode32Chars;
45+
var encode32Chars = s_encode32Chars;
4646

4747
buffer[12] = encode32Chars[value & 31];
4848
buffer[11] = encode32Chars[(value >> 5) & 31];

src/Http/Http/src/FormCollection.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ public StringValues this[string key]
7070
return StringValues.Empty;
7171
}
7272

73-
if (TryGetValue(key, out StringValues value))
73+
if (TryGetValue(key, out var value))
7474
{
7575
return value;
7676
}

src/Http/Http/src/HeaderDictionary.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ public StringValues this[string key]
7171
return StringValues.Empty;
7272
}
7373

74-
if (TryGetValue(key, out StringValues value))
74+
if (TryGetValue(key, out var value))
7575
{
7676
return value;
7777
}
@@ -227,7 +227,7 @@ public void Clear()
227227
public bool Contains(KeyValuePair<string, StringValues> item)
228228
{
229229
if (Store == null ||
230-
!Store.TryGetValue(item.Key, out StringValues value) ||
230+
!Store.TryGetValue(item.Key, out var value) ||
231231
!StringValues.Equals(value, item.Value))
232232
{
233233
return false;

src/Http/Http/src/Internal/DefaultHttpResponse.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ namespace Microsoft.AspNetCore.Http
1414
internal sealed class DefaultHttpResponse : HttpResponse
1515
{
1616
// Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624
17-
private readonly static Func<IFeatureCollection, IHttpResponseFeature?> _nullResponseFeature = f => null;
18-
private readonly static Func<IFeatureCollection, IHttpResponseBodyFeature?> _nullResponseBodyFeature = f => null;
19-
private readonly static Func<IFeatureCollection, IResponseCookiesFeature?> _newResponseCookiesFeature = f => new ResponseCookiesFeature(f);
17+
private static readonly Func<IFeatureCollection, IHttpResponseFeature?> _nullResponseFeature = f => null;
18+
private static readonly Func<IFeatureCollection, IHttpResponseBodyFeature?> _nullResponseBodyFeature = f => null;
19+
private static readonly Func<IFeatureCollection, IResponseCookiesFeature?> _newResponseCookiesFeature = f => new ResponseCookiesFeature(f);
2020

2121
private readonly DefaultHttpContext _context;
2222
private FeatureReferences<FeatureInterfaces> _features;

src/Http/Http/src/Internal/EventIds.cs

Lines changed: 0 additions & 12 deletions
This file was deleted.

src/Http/Http/src/Internal/ResponseCookies.cs

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Http
1414
/// <summary>
1515
/// A wrapper for the response Set-Cookie header.
1616
/// </summary>
17-
internal class ResponseCookies : IResponseCookies
17+
internal partial class ResponseCookies : IResponseCookies
1818
{
1919
internal const string EnableCookieNameEncoding = "Microsoft.AspNetCore.Http.EnableCookieNameEncoding";
2020
internal bool _enableCookieNameEncoding = AppContext.TryGetSwitch(EnableCookieNameEncoding, out var enabled) && enabled;
@@ -156,8 +156,8 @@ public void Delete(string key, CookieOptions options)
156156
}
157157

158158
var encodedKeyPlusEquals = (_enableCookieNameEncoding ? Uri.EscapeDataString(key) : key) + "=";
159-
bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
160-
bool pathHasValue = !string.IsNullOrEmpty(options.Path);
159+
var domainHasValue = !string.IsNullOrEmpty(options.Domain);
160+
var pathHasValue = !string.IsNullOrEmpty(options.Path);
161161

162162
Func<string, string, CookieOptions, bool> rejectPredicate;
163163
if (domainHasValue && pathHasValue)
@@ -212,17 +212,10 @@ public void Delete(string key, CookieOptions options)
212212
});
213213
}
214214

215-
private static class Log
215+
private static partial class Log
216216
{
217-
private static readonly Action<ILogger, string, Exception?> _samesiteNotSecure = LoggerMessage.Define<string>(
218-
LogLevel.Warning,
219-
EventIds.SameSiteNotSecure,
220-
"The cookie '{name}' has set 'SameSite=None' and must also set 'Secure'.");
221-
222-
public static void SameSiteCookieNotSecure(ILogger logger, string name)
223-
{
224-
_samesiteNotSecure(logger, name, null);
225-
}
217+
[LoggerMessage(1, LogLevel.Warning, "The cookie '{name}' has set 'SameSite=None' and must also set 'Secure'.", EventName = "SameSiteNotSecure")]
218+
public static partial void SameSiteCookieNotSecure(ILogger logger, string name);
226219
}
227220
}
228221
}

0 commit comments

Comments
 (0)