Skip to content

Commit 1852bb7

Browse files
authored
Enable CA1810 as a warning (#40384)
Contributes to #24055 Contributes to #32087 * This updates most of the repo to use LoggerMessageAttributes. MvcCoreLoggerExtensions is the only standout but it is fairly involved since it mixes logging from several types, re-uses logger ids etc
1 parent f23cfb8 commit 1852bb7

File tree

12 files changed

+99
-459
lines changed

12 files changed

+99
-459
lines changed

.editorconfig

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ dotnet_diagnostic.CA1802.severity = warning
9999
dotnet_diagnostic.CA1805.severity = warning
100100

101101
# CA1810: Do not initialize unnecessarily
102-
dotnet_diagnostic.CA1810.severity = suggestion
102+
dotnet_diagnostic.CA1810.severity = warning
103103

104104
# CA1821: Remove empty Finalizers
105105
dotnet_diagnostic.CA1821.severity = warning
@@ -268,6 +268,8 @@ dotnet_diagnostic.CA1507.severity = suggestion
268268
dotnet_diagnostic.CA1802.severity = suggestion
269269
# CA1805: Do not initialize unnecessarily
270270
dotnet_diagnostic.CA1805.severity = suggestion
271+
# CA1810: Do not initialize unnecessarily
272+
dotnet_diagnostic.CA1810.severity = suggestion
271273
# CA1822: Make member static
272274
dotnet_diagnostic.CA1822.severity = suggestion
273275
# CA1823: Avoid zero-length array allocations

src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,6 @@ public partial class StartupAnalyzer : DiagnosticAnalyzer
1212
[System.Diagnostics.CodeAnalysis.SuppressMessage("MicrosoftCodeAnalysisReleaseTracking", "RS2008:Enable analyzer release tracking")]
1313
internal static class Diagnostics
1414
{
15-
public static readonly ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics;
16-
17-
static Diagnostics()
18-
{
19-
SupportedDiagnostics = ImmutableArray.Create<DiagnosticDescriptor>(new[]
20-
{
21-
// ASP
22-
BuildServiceProviderShouldNotCalledInConfigureServicesMethod,
23-
IncorrectlyConfiguredAuthorizationMiddleware,
24-
25-
// MVC
26-
UnsupportedUseMvcWithEndpointRouting,
27-
});
28-
}
29-
3015
internal static readonly DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor(
3116
"ASP0000",
3217
"Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'",
@@ -53,5 +38,15 @@ static Diagnostics()
5338
DiagnosticSeverity.Warning,
5439
isEnabledByDefault: true,
5540
helpLinkUri: "https://aka.ms/AA64fv1");
41+
42+
public static readonly ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics = ImmutableArray.Create<DiagnosticDescriptor>(new[]
43+
{
44+
// ASP
45+
BuildServiceProviderShouldNotCalledInConfigureServicesMethod,
46+
IncorrectlyConfiguredAuthorizationMiddleware,
47+
48+
// MVC
49+
UnsupportedUseMvcWithEndpointRouting,
50+
});
5651
}
5752
}
Lines changed: 15 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,90 +1,28 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4-
#nullable disable
5-
64
namespace Microsoft.Extensions.Logging;
75

8-
internal static class LoggingExtensions
6+
internal static partial class LoggingExtensions
97
{
10-
private static readonly Action<ILogger, Exception> _invalidExpirationTime;
11-
private static readonly Action<ILogger, Exception> _userIdsNotEquals;
12-
private static readonly Action<ILogger, string, string, Exception> _purposeNotEquals;
13-
private static readonly Action<ILogger, Exception> _unexpectedEndOfInput;
14-
private static readonly Action<ILogger, Exception> _securityStampNotEquals;
15-
private static readonly Action<ILogger, Exception> _securityStampIsNotEmpty;
16-
private static readonly Action<ILogger, Exception> _unhandledException;
17-
18-
static LoggingExtensions()
19-
{
20-
_invalidExpirationTime = LoggerMessage.Define(
21-
eventId: new EventId(0, "InvalidExpirationTime"),
22-
logLevel: LogLevel.Debug,
23-
formatString: "ValidateAsync failed: the expiration time is invalid.");
24-
25-
_userIdsNotEquals = LoggerMessage.Define(
26-
eventId: new EventId(1, "UserIdsNotEquals"),
27-
logLevel: LogLevel.Debug,
28-
formatString: "ValidateAsync failed: did not find expected UserId.");
29-
30-
_purposeNotEquals = LoggerMessage.Define<string, string>(
31-
eventId: new EventId(2, "PurposeNotEquals"),
32-
logLevel: LogLevel.Debug,
33-
formatString: "ValidateAsync failed: did not find expected purpose. '{ActualPurpose}' does not match the expected purpose '{ExpectedPurpose}'.");
34-
35-
_unexpectedEndOfInput = LoggerMessage.Define(
36-
eventId: new EventId(3, "UnexpectedEndOfInput"),
37-
logLevel: LogLevel.Debug,
38-
formatString: "ValidateAsync failed: unexpected end of input.");
39-
40-
_securityStampNotEquals = LoggerMessage.Define(
41-
eventId: new EventId(4, "SecurityStampNotEquals"),
42-
logLevel: LogLevel.Debug,
43-
formatString: "ValidateAsync failed: did not find expected security stamp.");
44-
45-
_securityStampIsNotEmpty = LoggerMessage.Define(
46-
eventId: new EventId(5, "SecurityStampIsNotEmpty"),
47-
logLevel: LogLevel.Debug,
48-
formatString: "ValidateAsync failed: the expected stamp is not empty.");
49-
50-
_unhandledException = LoggerMessage.Define(
51-
eventId: new EventId(6, "UnhandledException"),
52-
logLevel: LogLevel.Debug,
53-
formatString: "ValidateAsync failed: unhandled exception was thrown.");
54-
}
55-
56-
public static void InvalidExpirationTime(this ILogger logger)
57-
{
58-
_invalidExpirationTime(logger, null);
59-
}
8+
[LoggerMessage(0, LogLevel.Debug, "ValidateAsync failed: the expiration time is invalid.", EventName = "InvalidExpirationTime")]
9+
public static partial void InvalidExpirationTime(this ILogger logger);
6010

61-
public static void UserIdsNotEquals(this ILogger logger)
62-
{
63-
_userIdsNotEquals(logger, null);
64-
}
11+
[LoggerMessage(1, LogLevel.Debug, "ValidateAsync failed: did not find expected UserId.", EventName = "UserIdsNotEquals")]
12+
public static partial void UserIdsNotEquals(this ILogger logger);
6513

66-
public static void PurposeNotEquals(this ILogger logger, string actualPurpose, string expectedPurpose)
67-
{
68-
_purposeNotEquals(logger, actualPurpose, expectedPurpose, null);
69-
}
14+
[LoggerMessage(2, LogLevel.Debug, "ValidateAsync failed: did not find expected purpose. '{ActualPurpose}' does not match the expected purpose '{ExpectedPurpose}'.", EventName = "PurposeNotEquals")]
15+
public static partial void PurposeNotEquals(this ILogger logger, string actualPurpose, string expectedPurpose);
7016

71-
public static void UnexpectedEndOfInput(this ILogger logger)
72-
{
73-
_unexpectedEndOfInput(logger, null);
74-
}
17+
[LoggerMessage(3, LogLevel.Debug, "ValidateAsync failed: unexpected end of input.", EventName = "UnexpectedEndOfInput")]
18+
public static partial void UnexpectedEndOfInput(this ILogger logger);
7519

76-
public static void SecurityStampNotEquals(this ILogger logger)
77-
{
78-
_securityStampNotEquals(logger, null);
79-
}
20+
[LoggerMessage(4, LogLevel.Debug, "ValidateAsync failed: did not find expected security stamp.", EventName = "SecurityStampNotEquals")]
21+
public static partial void SecurityStampNotEquals(this ILogger logger);
8022

81-
public static void SecurityStampIsNotEmpty(this ILogger logger)
82-
{
83-
_securityStampIsNotEmpty(logger, null);
84-
}
23+
[LoggerMessage(5, LogLevel.Debug, "ValidateAsync failed: the expected stamp is not empty.", EventName = "SecurityStampIsNotEmpty")]
24+
public static partial void SecurityStampIsNotEmpty(this ILogger logger);
8525

86-
public static void UnhandledException(this ILogger logger)
87-
{
88-
_unhandledException(logger, null);
89-
}
26+
[LoggerMessage(6, LogLevel.Debug, "ValidateAsync failed: unhandled exception was thrown.", EventName = "UnhandledException")]
27+
public static partial void UnhandledException(this ILogger logger);
9028
}

src/Localization/Localization/src/Internal/ResourceManagerStringLocalizerLoggerExtensions.cs

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

src/Localization/Localization/src/ResourceManagerStringLocalizer.cs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
using System.Linq;
99
using System.Reflection;
1010
using System.Resources;
11-
using Microsoft.Extensions.Localization.Internal;
1211
using Microsoft.Extensions.Logging;
1312

1413
namespace Microsoft.Extensions.Localization;
@@ -18,7 +17,7 @@ namespace Microsoft.Extensions.Localization;
1817
/// <see cref="ResourceReader"/> to provide localized strings.
1918
/// </summary>
2019
/// <remarks>This type is thread-safe.</remarks>
21-
public class ResourceManagerStringLocalizer : IStringLocalizer
20+
public partial class ResourceManagerStringLocalizer : IStringLocalizer
2221
{
2322
private readonly ConcurrentDictionary<string, object?> _missingManifestCache = new ConcurrentDictionary<string, object?>();
2423
private readonly IResourceNamesCache _resourceNamesCache;
@@ -193,7 +192,7 @@ protected IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures,
193192

194193
var cacheKey = $"name={name}&culture={keyCulture.Name}";
195194

196-
_logger.SearchedLocation(name, _resourceBaseName, keyCulture);
195+
Log.SearchedLocation(_logger, name, _resourceBaseName, keyCulture);
197196

198197
if (_missingManifestCache.ContainsKey(cacheKey))
199198
{
@@ -247,4 +246,10 @@ private IEnumerable<string> GetResourceNamesFromCultureHierarchy(CultureInfo sta
247246

248247
return resourceNames;
249248
}
249+
250+
private static partial class Log
251+
{
252+
[LoggerMessage(1, LogLevel.Debug, $"{nameof(ResourceManagerStringLocalizer)} searched for '{{Key}}' in '{{LocationSearched}}' with culture '{{Culture}}'.", EventName = "SearchedLocation")]
253+
public static partial void SearchedLocation(ILogger logger, string key, string locationSearched, CultureInfo culture);
254+
}
250255
}

src/Mvc/Mvc.Core/src/MvcCoreLoggerExtensions.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
#nullable disable
5+
#pragma warning disable CA1810 // Initialize all static fields inline.
56

67
using System.Collections;
78
using System.Globalization;

src/Mvc/Mvc.Razor/src/Compilation/DefaultViewCompiler.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,14 +96,14 @@ public Task<CompiledViewDescriptor> CompileAsync(string relativePath)
9696
// normalized and a cache entry exists.
9797
if (_compiledViews.TryGetValue(relativePath, out var cachedResult))
9898
{
99-
_logger.ViewCompilerLocatedCompiledViewForPath(relativePath);
99+
Log.ViewCompilerLocatedCompiledViewForPath(_logger, relativePath);
100100
return cachedResult;
101101
}
102102

103103
var normalizedPath = GetNormalizedPath(relativePath);
104104
if (_compiledViews.TryGetValue(normalizedPath, out cachedResult))
105105
{
106-
_logger.ViewCompilerLocatedCompiledViewForPath(normalizedPath);
106+
Log.ViewCompilerLocatedCompiledViewForPath(_logger, normalizedPath);
107107
return cachedResult;
108108
}
109109

@@ -141,6 +141,9 @@ private static partial class Log
141141
[LoggerMessage(4, LogLevel.Debug, "Initializing Razor view compiler with no compiled views.", EventName = "ViewCompilerNoCompiledViewsFound")]
142142
public static partial void ViewCompilerNoCompiledViewsFound(ILogger logger);
143143

144+
[LoggerMessage(5, LogLevel.Trace, "Located compiled view for view at path '{Path}'.", EventName = "ViewCompilerLocatedCompiledViewForPath")]
145+
public static partial void ViewCompilerLocatedCompiledViewForPath(ILogger logger, string path);
146+
144147
[LoggerMessage(7, LogLevel.Trace, "Could not find a file for view at path '{Path}'.", EventName = "ViewCompilerCouldNotFindFileAtPath")]
145148
public static partial void ViewCompilerCouldNotFindFileAtPath(ILogger logger, string path);
146149
}

0 commit comments

Comments
 (0)