Browse Source

Convert some LoggerMessage.Define to LoggerMessageAttribute (#34905)

Pranav K 4 years ago
parent
commit
90c08fe18c
25 changed files with 617 additions and 2569 deletions
  1. 133 708
      src/DataProtection/DataProtection/src/LoggingExtensions.cs
  2. 5 22
      src/DataProtection/EntityFrameworkCore/src/LoggingExtensions.cs
  3. 23 115
      src/Middleware/CORS/src/CORSLoggerExtensions.cs
  4. 10 32
      src/Middleware/ConcurrencyLimiter/src/ConcurrencyLimiterMiddleware.cs
  5. 35 129
      src/Middleware/Diagnostics.EntityFrameworkCore/src/DiagnosticsEntityFrameworkCoreLoggerExtensions.cs
  6. 14 39
      src/Middleware/Diagnostics/src/DiagnosticsLoggerExtensions.cs
  7. 8 22
      src/Middleware/HttpLogging/src/FileLoggerProcessor.cs
  8. 13 18
      src/Middleware/HttpLogging/src/HttpLoggingExtensions.cs
  9. 2 1
      src/Middleware/HttpLogging/src/W3CLoggerOptions.cs
  10. 3 15
      src/Middleware/HttpOverrides/src/LoggingExtensions.cs
  11. 29 146
      src/Middleware/Rewrite/src/Extensions/RewriteMiddlewareLoggingExtensions.cs
  12. 27 125
      src/Middleware/Session/src/LoggingExtensions.cs
  13. 28 120
      src/Middleware/StaticFiles/src/LoggerExtensions.cs
  14. 6 16
      src/Middleware/WebSockets/src/WebSocketMiddleware.cs
  15. 9 48
      src/Security/Authentication/Certificate/src/LoggingExtensions.cs
  16. 5 18
      src/Security/Authentication/Cookies/src/LoggingExtensions.cs
  17. 29 134
      src/Security/Authentication/Core/src/LoggingExtensions.cs
  18. 25 92
      src/Security/Authentication/Negotiate/src/Internal/NegotiateLoggingExtensions.cs
  19. 3 15
      src/Security/Authentication/OAuth/src/LoggingExtensions.cs
  20. 160 532
      src/Security/Authentication/OpenIdConnect/src/LoggingExtensions.cs
  21. 7 35
      src/Security/Authentication/Twitter/src/LoggingExtensions.cs
  22. 15 69
      src/Security/Authentication/WsFederation/src/LoggingExtensions.cs
  23. 6 13
      src/Security/Authorization/Core/src/LoggingExtensions.cs
  24. 19 89
      src/Security/CookiePolicy/src/LoggingExtensions.cs
  25. 3 16
      src/Shared/StackTrace/ExceptionDetails/LoggerExtensions.cs

+ 133 - 708
src/DataProtection/DataProtection/src/LoggingExtensions.cs

@@ -4,10 +4,7 @@
 using System;
 using System.Diagnostics.CodeAnalysis;
 using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Runtime.Versioning;
 using System.Xml.Linq;
-using Microsoft.AspNetCore.DataProtection;
 using Microsoft.Win32;
 
 namespace Microsoft.Extensions.Logging
@@ -15,414 +12,8 @@ namespace Microsoft.Extensions.Logging
     /// <summary>
     /// Helpful extension methods on <see cref="ILogger"/>.
     /// </summary>
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, Guid, DateTimeOffset, Exception?> _usingFallbackKeyWithExpirationAsDefaultKey;
-
-        private static readonly Action<ILogger, Guid, Exception?> _usingKeyAsDefaultKey;
-
-        private static readonly Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithHMAC;
-
-        private static readonly Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithChainingModeCBC;
-
-        private static readonly Action<ILogger, Guid, string, Exception?> _performingUnprotectOperationToKeyWithPurposes;
-
-        private static readonly Action<ILogger, Guid, Exception?> _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed;
-
-        private static readonly Action<ILogger, Guid, Exception?> _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless;
-
-        private static readonly Action<ILogger, Guid, Exception?> _keyWasRevokedUnprotectOperationCannotProceed;
-
-        private static readonly Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithChainingModeGCM;
-
-        private static readonly Action<ILogger, string, Exception?> _usingManagedKeyedHashAlgorithm;
-
-        private static readonly Action<ILogger, string, Exception?> _usingManagedSymmetricAlgorithm;
-
-        private static readonly Action<ILogger, Guid, string, Exception> _keyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed;
-
-        private static readonly Action<ILogger, Guid, DateTimeOffset, Exception?> _consideringKeyWithExpirationDateAsDefaultKey;
-
-        private static readonly Action<ILogger, Guid, Exception?> _keyIsNoLongerUnderConsiderationAsDefault;
-
-        private static readonly Action<ILogger, XName, Exception?> _unknownElementWithNameFoundInKeyringSkipping;
-
-        private static readonly Action<ILogger, Guid, Exception?> _markedKeyAsRevokedInTheKeyring;
-
-        private static readonly Action<ILogger, Guid, Exception?> _triedToProcessRevocationOfKeyButNoSuchKeyWasFound;
-
-        private static readonly Action<ILogger, Guid, Exception?> _foundKey;
-
-        private static readonly Action<ILogger, DateTimeOffset, Exception?> _foundRevocationOfAllKeysCreatedPriorTo;
-
-        private static readonly Action<ILogger, Guid, Exception?> _foundRevocationOfKey;
-
-        private static readonly Action<ILogger, XElement, Exception> _exceptionWhileProcessingRevocationElement;
-
-        private static readonly Action<ILogger, DateTimeOffset, string?, Exception?> _revokingAllKeysAsOfForReason;
-
-        private static readonly Action<ILogger, string, Exception?> _keyCacheExpirationTokenTriggeredByOperation;
-
-        private static readonly Action<ILogger, XElement, Exception> _anExceptionOccurredWhileProcessingTheKeyElement;
-
-        private static readonly Action<ILogger, XElement, Exception> _anExceptionOccurredWhileProcessingTheKeyElementDebug;
-
-        private static readonly Action<ILogger, string, Exception?> _encryptingToWindowsDPAPIForCurrentUserAccount;
-
-        private static readonly Action<ILogger, string, Exception?> _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule;
-
-        private static readonly Action<ILogger, string, Exception> _anErrorOccurredWhileEncryptingToX509CertificateWithThumbprint;
-
-        private static readonly Action<ILogger, string, Exception?> _encryptingToX509CertificateWithThumbprint;
-
-        private static readonly Action<ILogger, string, Exception> _exceptionOccurredWhileTryingToResolveCertificateWithThumbprint;
-
-        private static readonly Action<ILogger, Guid, string, Exception?> _performingProtectOperationToKeyWithPurposes;
-
-        private static readonly Action<ILogger, Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset, Exception?> _creatingKey;
-
-        private static readonly Action<ILogger, Guid, string, Exception?> _descriptorDeserializerTypeForKeyIs;
-
-        private static readonly Action<ILogger, Guid, Exception?> _keyEscrowSinkFoundWritingKeyToEscrow;
-
-        private static readonly Action<ILogger, Guid, Exception?> _noKeyEscrowSinkFoundNotWritingKeyToEscrow;
-
-        private static readonly Action<ILogger, Guid, Exception?> _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm;
-
-        private static readonly Action<ILogger, Guid, DateTimeOffset, string?, Exception?> _revokingKeyForReason;
-
-        private static readonly Action<ILogger, string, Exception?> _readingDataFromFile;
-
-        private static readonly Action<ILogger, string, string, Exception?> _nameIsNotSafeFileName;
-
-        private static readonly Action<ILogger, string, Exception?> _writingDataToFile;
-
-        private static readonly Action<ILogger, RegistryKey, string, Exception?>? _readingDataFromRegistryKeyValue;
-
-        private static readonly Action<ILogger, string, string, Exception?> _nameIsNotSafeRegistryValueName;
-
-        private static readonly Action<ILogger, string?, Exception?> _decryptingSecretElementUsingWindowsDPAPING;
-
-        private static readonly Action<ILogger, Exception> _exceptionOccurredTryingToDecryptElement;
-
-        private static readonly Action<ILogger, Exception?> _encryptingUsingNullEncryptor;
-
-        private static readonly Action<ILogger, Exception?> _usingEphemeralDataProtectionProvider;
-
-        private static readonly Action<ILogger, Exception?> _existingCachedKeyRingIsExpiredRefreshing;
-
-        private static readonly Action<ILogger, Exception> _errorOccurredWhileRefreshingKeyRing;
-
-        private static readonly Action<ILogger, Exception> _errorOccurredWhileReadingKeyRing;
-
-        private static readonly Action<ILogger, Exception?> _keyRingDoesNotContainValidDefaultKey;
-
-        private static readonly Action<ILogger, Exception?> _usingInmemoryRepository;
-
-        private static readonly Action<ILogger, Exception?> _decryptingSecretElementUsingWindowsDPAPI;
-
-        private static readonly Action<ILogger, Exception?> _defaultKeyExpirationImminentAndRepository;
-
-        private static readonly Action<ILogger, Exception?> _repositoryContainsNoViableDefaultKey;
-
-        private static readonly Action<ILogger, Exception> _errorOccurredWhileEncryptingToWindowsDPAPI;
-
-        private static readonly Action<ILogger, Exception?> _encryptingToWindowsDPAPIForLocalMachineAccount;
-
-        private static readonly Action<ILogger, Exception> _errorOccurredWhileEncryptingToWindowsDPAPING;
-
-        private static readonly Action<ILogger, Exception?> _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing;
-
-        private static readonly Action<ILogger, Guid, Exception?> _keyRingWasLoadedOnStartup;
-
-        private static readonly Action<ILogger, Exception> _keyRingFailedToLoadOnStartup;
-
-        private static readonly Action<ILogger, Exception?> _usingEphemeralKeyRepository;
-
-        private static readonly Action<ILogger, string, Exception?> _usingRegistryAsKeyRepositoryWithDPAPI;
-
-        private static readonly Action<ILogger, string, Exception?> _usingProfileAsKeyRepository;
-
-        private static readonly Action<ILogger, string, Exception?> _usingProfileAsKeyRepositoryWithDPAPI;
-
-        private static readonly Action<ILogger, string, Exception?> _usingAzureAsKeyRepository;
-
-        private static readonly Action<ILogger, string, Exception?> _usingEphemeralFileSystemLocationInContainer;
-
-        static LoggingExtensions()
-        {
-            _usingFallbackKeyWithExpirationAsDefaultKey = LoggerMessage.Define<Guid, DateTimeOffset>(
-                eventId: new EventId(1, "UsingFallbackKeyWithExpirationAsDefaultKey"),
-                logLevel: LogLevel.Warning,
-                formatString: "Policy resolution states that a new key should be added to the key ring, but automatic generation of keys is disabled. Using fallback key {KeyId:B} with expiration {ExpirationDate:u} as default key.");
-            _usingKeyAsDefaultKey = LoggerMessage.Define<Guid>(
-                eventId: new EventId(2, "UsingKeyAsDefaultKey"),
-                logLevel: LogLevel.Debug,
-                formatString: "Using key {KeyId:B} as the default key.");
-            _openingCNGAlgorithmFromProviderWithHMAC = LoggerMessage.Define<string, string?>(
-                eventId: new EventId(3, "OpeningCNGAlgorithmFromProviderWithHMAC"),
-                logLevel: LogLevel.Debug,
-                formatString: "Opening CNG algorithm '{HashAlgorithm}' from provider '{HashAlgorithmProvider}' with HMAC.");
-            _openingCNGAlgorithmFromProviderWithChainingModeCBC = LoggerMessage.Define<string, string?>(
-                eventId: new EventId(4, "OpeningCNGAlgorithmFromProviderWithChainingModeCBC"),
-                logLevel: LogLevel.Debug,
-                formatString: "Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode CBC.");
-            _performingUnprotectOperationToKeyWithPurposes = LoggerMessage.Define<Guid, string>(
-                eventId: new EventId(5, "PerformingUnprotectOperationToKeyWithPurposes"),
-                logLevel: LogLevel.Trace,
-                formatString: "Performing unprotect operation to key {KeyId:B} with purposes {Purposes}.");
-            _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed = LoggerMessage.Define<Guid>(
-                eventId: new EventId(6, "KeyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed"),
-                logLevel: LogLevel.Trace,
-                formatString: "Key {KeyId:B} was not found in the key ring. Unprotect operation cannot proceed.");
-            _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless = LoggerMessage.Define<Guid>(
-                eventId: new EventId(7, "KeyWasRevokedCallerRequestedUnprotectOperationProceedRegardless"),
-                logLevel: LogLevel.Debug,
-                formatString: "Key {KeyId:B} was revoked. Caller requested unprotect operation proceed regardless.");
-            _keyWasRevokedUnprotectOperationCannotProceed = LoggerMessage.Define<Guid>(
-                eventId: new EventId(8, "KeyWasRevokedUnprotectOperationCannotProceed"),
-                logLevel: LogLevel.Debug,
-                formatString: "Key {KeyId:B} was revoked. Unprotect operation cannot proceed.");
-            _openingCNGAlgorithmFromProviderWithChainingModeGCM = LoggerMessage.Define<string, string?>(
-                eventId: new EventId(9, "OpeningCNGAlgorithmFromProviderWithChainingModeGCM"),
-                logLevel: LogLevel.Debug,
-                formatString: "Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode GCM.");
-            _usingManagedKeyedHashAlgorithm = LoggerMessage.Define<string>(
-                eventId: new EventId(10, "UsingManagedKeyedHashAlgorithm"),
-                logLevel: LogLevel.Debug,
-                formatString: "Using managed keyed hash algorithm '{FullName}'.");
-            _usingManagedSymmetricAlgorithm = LoggerMessage.Define<string>(
-                eventId: new EventId(11, "UsingManagedSymmetricAlgorithm"),
-                logLevel: LogLevel.Debug,
-                formatString: "Using managed symmetric algorithm '{FullName}'.");
-            _keyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed = LoggerMessage.Define<Guid, string>(
-                eventId: new EventId(12, "KeyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed"),
-                logLevel: LogLevel.Warning,
-                formatString: "Key {KeyId:B} is ineligible to be the default key because its {MethodName} method failed.");
-            _consideringKeyWithExpirationDateAsDefaultKey = LoggerMessage.Define<Guid, DateTimeOffset>(
-                eventId: new EventId(13, "ConsideringKeyWithExpirationDateAsDefaultKey"),
-                logLevel: LogLevel.Debug,
-                formatString: "Considering key {KeyId:B} with expiration date {ExpirationDate:u} as default key.");
-            _keyIsNoLongerUnderConsiderationAsDefault = LoggerMessage.Define<Guid>(
-                eventId: new EventId(14, "KeyIsNoLongerUnderConsiderationAsDefault"),
-                logLevel: LogLevel.Debug,
-                formatString: "Key {KeyId:B} is no longer under consideration as default key because it is expired, revoked, or cannot be deciphered.");
-            _unknownElementWithNameFoundInKeyringSkipping = LoggerMessage.Define<XName>(
-                eventId: new EventId(15, "UnknownElementWithNameFoundInKeyringSkipping"),
-                logLevel: LogLevel.Warning,
-                formatString: "Unknown element with name '{Name}' found in keyring, skipping.");
-            _markedKeyAsRevokedInTheKeyring = LoggerMessage.Define<Guid>(
-                eventId: new EventId(16, "MarkedKeyAsRevokedInTheKeyring"),
-                logLevel: LogLevel.Debug,
-                formatString: "Marked key {KeyId:B} as revoked in the keyring.");
-            _triedToProcessRevocationOfKeyButNoSuchKeyWasFound = LoggerMessage.Define<Guid>(
-                eventId: new EventId(17, "TriedToProcessRevocationOfKeyButNoSuchKeyWasFound"),
-                logLevel: LogLevel.Warning,
-                formatString: "Tried to process revocation of key {KeyId:B}, but no such key was found in keyring. Skipping.");
-            _foundKey = LoggerMessage.Define<Guid>(
-                eventId: new EventId(18, "FoundKey"),
-                logLevel: LogLevel.Debug,
-                formatString: "Found key {KeyId:B}.");
-            _foundRevocationOfAllKeysCreatedPriorTo = LoggerMessage.Define<DateTimeOffset>(
-                eventId: new EventId(19, "FoundRevocationOfAllKeysCreatedPriorTo"),
-                logLevel: LogLevel.Debug,
-                formatString: "Found revocation of all keys created prior to {RevocationDate:u}.");
-            _foundRevocationOfKey = LoggerMessage.Define<Guid>(
-                eventId: new EventId(20, "FoundRevocationOfKey"),
-                logLevel: LogLevel.Debug,
-                formatString: "Found revocation of key {KeyId:B}.");
-            _exceptionWhileProcessingRevocationElement = LoggerMessage.Define<XElement>(
-                eventId: new EventId(21, "ExceptionWhileProcessingRevocationElement"),
-                logLevel: LogLevel.Error,
-                formatString: "An exception occurred while processing the revocation element '{RevocationElement}'. Cannot continue keyring processing.");
-            _revokingAllKeysAsOfForReason = LoggerMessage.Define<DateTimeOffset, string?>(
-                eventId: new EventId(22, "RevokingAllKeysAsOfForReason"),
-                logLevel: LogLevel.Information,
-                formatString: "Revoking all keys as of {RevocationDate:u} for reason '{Reason}'.");
-            _keyCacheExpirationTokenTriggeredByOperation = LoggerMessage.Define<string>(
-                eventId: new EventId(23, "KeyCacheExpirationTokenTriggeredByOperation"),
-                logLevel: LogLevel.Debug,
-                formatString: "Key cache expiration token triggered by '{OperationName}' operation.");
-            _anExceptionOccurredWhileProcessingTheKeyElement = LoggerMessage.Define<XElement>(
-                eventId: new EventId(24, "ExceptionOccurredWhileProcessingTheKeyElement"),
-                logLevel: LogLevel.Error,
-                formatString: "An exception occurred while processing the key element '{Element}'.");
-            _anExceptionOccurredWhileProcessingTheKeyElementDebug = LoggerMessage.Define<XElement>(
-                eventId: new EventId(25, "ExceptionOccurredWhileProcessingTheKeyElementDebug"),
-                logLevel: LogLevel.Trace,
-                formatString: "An exception occurred while processing the key element '{Element}'.");
-            _encryptingToWindowsDPAPIForCurrentUserAccount = LoggerMessage.Define<string>(
-                eventId: new EventId(26, "EncryptingToWindowsDPAPIForCurrentUserAccount"),
-                logLevel: LogLevel.Debug,
-                formatString: "Encrypting to Windows DPAPI for current user account ({Name}).");
-            _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule = LoggerMessage.Define<string>(
-                eventId: new EventId(27, "EncryptingToWindowsDPAPINGUsingProtectionDescriptorRule"),
-                logLevel: LogLevel.Debug,
-                formatString: "Encrypting to Windows DPAPI-NG using protection descriptor rule '{DescriptorRule}'.");
-            _anErrorOccurredWhileEncryptingToX509CertificateWithThumbprint = LoggerMessage.Define<string>(
-                eventId: new EventId(28, "ErrorOccurredWhileEncryptingToX509CertificateWithThumbprint"),
-                logLevel: LogLevel.Error,
-                formatString: "An error occurred while encrypting to X.509 certificate with thumbprint '{Thumbprint}'.");
-            _encryptingToX509CertificateWithThumbprint = LoggerMessage.Define<string>(
-                eventId: new EventId(29, "EncryptingToX509CertificateWithThumbprint"),
-                logLevel: LogLevel.Debug,
-                formatString: "Encrypting to X.509 certificate with thumbprint '{Thumbprint}'.");
-            _exceptionOccurredWhileTryingToResolveCertificateWithThumbprint = LoggerMessage.Define<string>(
-                eventId: new EventId(30, "ExceptionOccurredWhileTryingToResolveCertificateWithThumbprint"),
-                logLevel: LogLevel.Error,
-                formatString: "An exception occurred while trying to resolve certificate with thumbprint '{Thumbprint}'.");
-            _performingProtectOperationToKeyWithPurposes = LoggerMessage.Define<Guid, string>(
-                eventId: new EventId(31, "PerformingProtectOperationToKeyWithPurposes"),
-                logLevel: LogLevel.Trace,
-                formatString: "Performing protect operation to key {KeyId:B} with purposes {Purposes}.");
-            _descriptorDeserializerTypeForKeyIs = LoggerMessage.Define<Guid, string>(
-                eventId: new EventId(32, "DescriptorDeserializerTypeForKeyIs"),
-                logLevel: LogLevel.Debug,
-                formatString: "Descriptor deserializer type for key {KeyId:B} is '{AssemblyQualifiedName}'.");
-            _keyEscrowSinkFoundWritingKeyToEscrow = LoggerMessage.Define<Guid>(
-                eventId: new EventId(33, "KeyEscrowSinkFoundWritingKeyToEscrow"),
-                logLevel: LogLevel.Debug,
-                formatString: "Key escrow sink found. Writing key {KeyId:B} to escrow.");
-            _noKeyEscrowSinkFoundNotWritingKeyToEscrow = LoggerMessage.Define<Guid>(
-                eventId: new EventId(34, "NoKeyEscrowSinkFoundNotWritingKeyToEscrow"),
-                logLevel: LogLevel.Debug,
-                formatString: "No key escrow sink found. Not writing key {KeyId:B} to escrow.");
-            _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm = LoggerMessage.Define<Guid>(
-                eventId: new EventId(35, "NoXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm"),
-                logLevel: LogLevel.Warning,
-                formatString: "No XML encryptor configured. Key {KeyId:B} may be persisted to storage in unencrypted form.");
-            _revokingKeyForReason = LoggerMessage.Define<Guid, DateTimeOffset, string?>(
-                eventId: new EventId(36, "RevokingKeyForReason"),
-                logLevel: LogLevel.Information,
-                formatString: "Revoking key {KeyId:B} at {RevocationDate:u} for reason '{Reason}'.");
-            _readingDataFromFile = LoggerMessage.Define<string>(
-                eventId: new EventId(37, "ReadingDataFromFile"),
-                logLevel: LogLevel.Debug,
-                formatString: "Reading data from file '{FullPath}'.");
-            _nameIsNotSafeFileName = LoggerMessage.Define<string, string>(
-                eventId: new EventId(38, "NameIsNotSafeFileName"),
-                logLevel: LogLevel.Debug,
-                formatString: "The name '{FriendlyName}' is not a safe file name, using '{NewFriendlyName}' instead.");
-            _writingDataToFile = LoggerMessage.Define<string>(
-                eventId: new EventId(39, "WritingDataToFile"),
-                logLevel: LogLevel.Information,
-                formatString: "Writing data to file '{FileName}'.");
-
-            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
-            {
-                _readingDataFromRegistryKeyValue = LoggerMessage.Define<RegistryKey, string>(
-                    eventId: new EventId(40, "ReadingDataFromRegistryKeyValue"),
-                    logLevel: LogLevel.Debug,
-                    formatString: "Reading data from registry key '{RegistryKeyName}', value '{Value}'.");
-            }
-
-            _nameIsNotSafeRegistryValueName = LoggerMessage.Define<string, string>(
-                eventId: new EventId(41, "NameIsNotSafeRegistryValueName"),
-                logLevel: LogLevel.Debug,
-                formatString: "The name '{FriendlyName}' is not a safe registry value name, using '{NewFriendlyName}' instead.");
-            _decryptingSecretElementUsingWindowsDPAPING = LoggerMessage.Define<string?>(
-                eventId: new EventId(42, "DecryptingSecretElementUsingWindowsDPAPING"),
-                logLevel: LogLevel.Debug,
-                formatString: "Decrypting secret element using Windows DPAPI-NG with protection descriptor rule '{DescriptorRule}'.");
-            _exceptionOccurredTryingToDecryptElement = LoggerMessage.Define(
-                eventId: new EventId(43, "ExceptionOccurredTryingToDecryptElement"),
-                logLevel: LogLevel.Error,
-                formatString: "An exception occurred while trying to decrypt the element.");
-            _encryptingUsingNullEncryptor = LoggerMessage.Define(
-                eventId: new EventId(44, "EncryptingUsingNullEncryptor"),
-                logLevel: LogLevel.Warning,
-                formatString: "Encrypting using a null encryptor; secret information isn't being protected.");
-            _usingEphemeralDataProtectionProvider = LoggerMessage.Define(
-                eventId: new EventId(45, "UsingEphemeralDataProtectionProvider"),
-                logLevel: LogLevel.Information,
-                formatString: "Using ephemeral data protection provider. Payloads will be undecipherable upon application shutdown.");
-            _existingCachedKeyRingIsExpiredRefreshing = LoggerMessage.Define(
-                eventId: new EventId(46, "ExistingCachedKeyRingIsExpiredRefreshing"),
-                logLevel: LogLevel.Debug,
-                formatString: "Existing cached key ring is expired. Refreshing.");
-            _errorOccurredWhileRefreshingKeyRing = LoggerMessage.Define(
-                eventId: new EventId(47, "ErrorOccurredWhileRefreshingKeyRing"),
-                logLevel: LogLevel.Error,
-                formatString: "An error occurred while refreshing the key ring. Will try again in 2 minutes.");
-            _errorOccurredWhileReadingKeyRing = LoggerMessage.Define(
-                eventId: new EventId(48, "ErrorOccurredWhileReadingKeyRing"),
-                logLevel: LogLevel.Error,
-                formatString: "An error occurred while reading the key ring.");
-            _keyRingDoesNotContainValidDefaultKey = LoggerMessage.Define(
-                eventId: new EventId(49, "KeyRingDoesNotContainValidDefaultKey"),
-                logLevel: LogLevel.Error,
-                formatString: "The key ring does not contain a valid default key, and the key manager is configured with auto-generation of keys disabled.");
-            _usingInmemoryRepository = LoggerMessage.Define(
-                eventId: new EventId(50, "UsingInMemoryRepository"),
-                logLevel: LogLevel.Warning,
-                formatString: "Using an in-memory repository. Keys will not be persisted to storage.");
-            _decryptingSecretElementUsingWindowsDPAPI = LoggerMessage.Define(
-                eventId: new EventId(51, "DecryptingSecretElementUsingWindowsDPAPI"),
-                logLevel: LogLevel.Debug,
-                formatString: "Decrypting secret element using Windows DPAPI.");
-            _defaultKeyExpirationImminentAndRepository = LoggerMessage.Define(
-                eventId: new EventId(52, "DefaultKeyExpirationImminentAndRepository"),
-                logLevel: LogLevel.Debug,
-                formatString: "Default key expiration imminent and repository contains no viable successor. Caller should generate a successor.");
-            _repositoryContainsNoViableDefaultKey = LoggerMessage.Define(
-                eventId: new EventId(53, "RepositoryContainsNoViableDefaultKey"),
-                logLevel: LogLevel.Debug,
-                formatString: "Repository contains no viable default key. Caller should generate a key with immediate activation.");
-            _errorOccurredWhileEncryptingToWindowsDPAPI = LoggerMessage.Define(
-                eventId: new EventId(54, "ErrorOccurredWhileEncryptingToWindowsDPAPI"),
-                logLevel: LogLevel.Error,
-                formatString: "An error occurred while encrypting to Windows DPAPI.");
-            _encryptingToWindowsDPAPIForLocalMachineAccount = LoggerMessage.Define(
-                eventId: new EventId(55, "EncryptingToWindowsDPAPIForLocalMachineAccount"),
-                logLevel: LogLevel.Debug,
-                formatString: "Encrypting to Windows DPAPI for local machine account.");
-            _errorOccurredWhileEncryptingToWindowsDPAPING = LoggerMessage.Define(
-                eventId: new EventId(56, "ErrorOccurredWhileEncryptingToWindowsDPAPING"),
-                logLevel: LogLevel.Error,
-                formatString: "An error occurred while encrypting to Windows DPAPI-NG.");
-            _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing = LoggerMessage.Define(
-                eventId: new EventId(57, "PolicyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing"),
-                logLevel: LogLevel.Debug,
-                formatString: "Policy resolution states that a new key should be added to the key ring.");
-            _creatingKey = LoggerMessage.Define<Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset>(
-                eventId: new EventId(58, "CreatingKey"),
-                logLevel: LogLevel.Information,
-                formatString: "Creating key {KeyId:B} with creation date {CreationDate:u}, activation date {ActivationDate:u}, and expiration date {ExpirationDate:u}.");
-            _usingEphemeralKeyRepository = LoggerMessage.Define(
-                eventId: new EventId(59, "UsingEphemeralKeyRepository"),
-                logLevel: LogLevel.Warning,
-                formatString: "Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.");
-            _usingEphemeralFileSystemLocationInContainer = LoggerMessage.Define<string>(
-                eventId: new EventId(60, "UsingEphemeralFileSystemLocationInContainer"),
-                logLevel: LogLevel.Warning,
-                formatString: Resources.FileSystem_EphemeralKeysLocationInContainer);
-
-            _usingRegistryAsKeyRepositoryWithDPAPI = LoggerMessage.Define<string>(
-                eventId: new EventId(61, "UsingRegistryAsKeyRepositoryWithDPAPI"),
-                logLevel: LogLevel.Information,
-                formatString: "User profile not available. Using '{Name}' as key repository and Windows DPAPI to encrypt keys at rest.");
-            _usingProfileAsKeyRepository = LoggerMessage.Define<string>(
-                eventId: new EventId(62, "UsingProfileAsKeyRepository"),
-                logLevel: LogLevel.Information,
-                formatString: "User profile is available. Using '{FullName}' as key repository; keys will not be encrypted at rest.");
-            _usingProfileAsKeyRepositoryWithDPAPI = LoggerMessage.Define<string>(
-                eventId: new EventId(63, "UsingProfileAsKeyRepositoryWithDPAPI"),
-                logLevel: LogLevel.Information,
-                formatString: "User profile is available. Using '{FullName}' as key repository and Windows DPAPI to encrypt keys at rest.");
-            _usingAzureAsKeyRepository = LoggerMessage.Define<string>(
-                eventId: new EventId(64, "UsingAzureAsKeyRepository"),
-                logLevel: LogLevel.Information,
-                formatString: "Azure Web Sites environment detected. Using '{FullName}' as key repository; keys will not be encrypted at rest.");
-            _keyRingWasLoadedOnStartup = LoggerMessage.Define<Guid>(
-                eventId: new EventId(65, "KeyRingWasLoadedOnStartup"),
-                logLevel: LogLevel.Debug,
-                formatString: "Key ring with default key {KeyId:B} was loaded during application startup.");
-            _keyRingFailedToLoadOnStartup = LoggerMessage.Define(
-                eventId: new EventId(66, "KeyRingFailedToLoadOnStartup"),
-                logLevel: LogLevel.Information,
-                formatString: "Key ring failed to load during application startup.");
-        }
-
         /// <summary>
         /// Returns a value stating whether the 'debug' log level is enabled.
         /// Returns false if the logger instance is null.
@@ -433,26 +24,6 @@ namespace Microsoft.Extensions.Logging
             return IsLogLevelEnabledCore(logger, LogLevel.Debug);
         }
 
-        /// <summary>
-        /// Returns a value stating whether the 'error' log level is enabled.
-        /// Returns false if the logger instance is null.
-        /// </summary>
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static bool IsErrorLevelEnabled([NotNullWhen(true)] this ILogger? logger)
-        {
-            return IsLogLevelEnabledCore(logger, LogLevel.Error);
-        }
-
-        /// <summary>
-        /// Returns a value stating whether the 'information' log level is enabled.
-        /// Returns false if the logger instance is null.
-        /// </summary>
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static bool IsInformationLevelEnabled([NotNullWhen(true)] this ILogger? logger)
-        {
-            return IsLogLevelEnabledCore(logger, LogLevel.Information);
-        }
-
         /// <summary>
         /// Returns a value stating whether the 'trace' log level is enabled.
         /// Returns false if the logger instance is null.
@@ -463,354 +34,208 @@ namespace Microsoft.Extensions.Logging
             return IsLogLevelEnabledCore(logger, LogLevel.Trace);
         }
 
-        /// <summary>
-        /// Returns a value stating whether the 'warning' log level is enabled.
-        /// Returns false if the logger instance is null.
-        /// </summary>
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public static bool IsWarningLevelEnabled([NotNullWhen(true)] this ILogger? logger)
-        {
-            return IsLogLevelEnabledCore(logger, LogLevel.Warning);
-        }
-
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
         private static bool IsLogLevelEnabledCore([NotNullWhen(true)] ILogger? logger, LogLevel level)
         {
             return (logger != null && logger.IsEnabled(level));
         }
 
-        public static void UsingFallbackKeyWithExpirationAsDefaultKey(this ILogger logger, Guid keyId, DateTimeOffset expirationDate)
-        {
-            _usingFallbackKeyWithExpirationAsDefaultKey(logger, keyId, expirationDate, null);
-        }
+        [LoggerMessage(1, LogLevel.Warning, "Policy resolution states that a new key should be added to the key ring, but automatic generation of keys is disabled. Using fallback key {KeyId:B} with expiration {ExpirationDate:u} as default key.", EventName = "UsingFallbackKeyWithExpirationAsDefaultKey")]
+        public static partial void UsingFallbackKeyWithExpirationAsDefaultKey(this ILogger logger, Guid keyId, DateTimeOffset expirationDate);
 
-        public static void UsingKeyAsDefaultKey(this ILogger logger, Guid keyId)
-        {
-            _usingKeyAsDefaultKey(logger, keyId, null);
-        }
+        [LoggerMessage(2, LogLevel.Debug, "Using key {KeyId:B} as the default key.", EventName = "UsingKeyAsDefaultKey")]
+        public static partial void UsingKeyAsDefaultKey(this ILogger logger, Guid keyId);
 
-        public static void OpeningCNGAlgorithmFromProviderWithHMAC(this ILogger logger, string hashAlgorithm, string? hashAlgorithmProvider)
-        {
-            _openingCNGAlgorithmFromProviderWithHMAC(logger, hashAlgorithm, hashAlgorithmProvider, null);
-        }
+        [LoggerMessage(3, LogLevel.Debug, "Opening CNG algorithm '{HashAlgorithm}' from provider '{HashAlgorithmProvider}' with HMAC.", EventName = "OpeningCNGAlgorithmFromProviderWithHMAC")]
+        public static partial void OpeningCNGAlgorithmFromProviderWithHMAC(this ILogger logger, string hashAlgorithm, string? hashAlgorithmProvider);
 
-        public static void OpeningCNGAlgorithmFromProviderWithChainingModeCBC(this ILogger logger, string encryptionAlgorithm, string? encryptionAlgorithmProvider)
-        {
-            _openingCNGAlgorithmFromProviderWithChainingModeCBC(logger, encryptionAlgorithm, encryptionAlgorithmProvider, null);
-        }
+        [LoggerMessage(4, LogLevel.Debug, "Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode CBC.", EventName = "OpeningCNGAlgorithmFromProviderWithChainingModeCBC")]
+        public static partial void OpeningCNGAlgorithmFromProviderWithChainingModeCBC(this ILogger logger, string encryptionAlgorithm, string? encryptionAlgorithmProvider);
 
-        public static void PerformingUnprotectOperationToKeyWithPurposes(this ILogger logger, Guid keyIdFromPayload, string p0)
-        {
-            _performingUnprotectOperationToKeyWithPurposes(logger, keyIdFromPayload, p0, null);
-        }
+        [LoggerMessage(5, LogLevel.Trace, "Performing unprotect operation to key {KeyId:B} with purposes {Purposes}.", EventName = "PerformingUnprotectOperationToKeyWithPurposes")]
+        public static partial void PerformingUnprotectOperationToKeyWithPurposes(this ILogger logger, Guid keyId, string purposes);
 
-        public static void KeyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed(this ILogger logger, Guid keyIdFromPayload)
-        {
-            _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed(logger, keyIdFromPayload, null);
-        }
+        [LoggerMessage(6, LogLevel.Trace, "Key {KeyId:B} was not found in the key ring. Unprotect operation cannot proceed.", EventName = "KeyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed")]
+        public static partial void KeyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed(this ILogger logger, Guid keyId);
 
-        public static void KeyWasRevokedCallerRequestedUnprotectOperationProceedRegardless(this ILogger logger, Guid keyIdFromPayload)
-        {
-            _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless(logger, keyIdFromPayload, null);
-        }
+        [LoggerMessage(7, LogLevel.Debug, "Key {KeyId:B} was revoked. Caller requested unprotect operation proceed regardless.", EventName = "KeyWasRevokedCallerRequestedUnprotectOperationProceedRegardless")]
+        public static partial void KeyWasRevokedCallerRequestedUnprotectOperationProceedRegardless(this ILogger logger, Guid keyId);
 
-        public static void KeyWasRevokedUnprotectOperationCannotProceed(this ILogger logger, Guid keyIdFromPayload)
-        {
-            _keyWasRevokedUnprotectOperationCannotProceed(logger, keyIdFromPayload, null);
-        }
+        [LoggerMessage(8, LogLevel.Debug, "Key {KeyId:B} was revoked. Unprotect operation cannot proceed.", EventName = "KeyWasRevokedUnprotectOperationCannotProceed")]
+        public static partial void KeyWasRevokedUnprotectOperationCannotProceed(this ILogger logger, Guid keyId);
 
-        public static void OpeningCNGAlgorithmFromProviderWithChainingModeGCM(this ILogger logger, string encryptionAlgorithm, string? encryptionAlgorithmProvider)
-        {
-            _openingCNGAlgorithmFromProviderWithChainingModeGCM(logger, encryptionAlgorithm, encryptionAlgorithmProvider, null);
-        }
+        [LoggerMessage(9, LogLevel.Debug, "Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode GCM.", EventName = "OpeningCNGAlgorithmFromProviderWithChainingModeGCM")]
+        public static partial void OpeningCNGAlgorithmFromProviderWithChainingModeGCM(this ILogger logger, string encryptionAlgorithm, string? encryptionAlgorithmProvider);
 
-        public static void UsingManagedKeyedHashAlgorithm(this ILogger logger, string fullName)
-        {
-            _usingManagedKeyedHashAlgorithm(logger, fullName, null);
-        }
+        [LoggerMessage(10, LogLevel.Debug, "Using managed keyed hash algorithm '{FullName}'.", EventName = "UsingManagedKeyedHashAlgorithm")]
+        public static partial void UsingManagedKeyedHashAlgorithm(this ILogger logger, string fullName);
 
-        public static void UsingManagedSymmetricAlgorithm(this ILogger logger, string fullName)
-        {
-            _usingManagedSymmetricAlgorithm(logger, fullName, null);
-        }
+        [LoggerMessage(11, LogLevel.Debug, "Using managed symmetric algorithm '{FullName}'.", EventName = "UsingManagedSymmetricAlgorithm")]
+        public static partial void UsingManagedSymmetricAlgorithm(this ILogger logger, string fullName);
 
-        public static void KeyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed(this ILogger logger, Guid keyId, string p0, Exception exception)
-        {
-            _keyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed(logger, keyId, p0, exception);
-        }
+        [LoggerMessage(12, LogLevel.Warning, "Key {KeyId:B} is ineligible to be the default key because its {MethodName} method failed.", EventName = "KeyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed")]
+        public static partial void KeyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed(this ILogger logger, Guid keyId, string methodName, Exception exception);
 
-        public static void ConsideringKeyWithExpirationDateAsDefaultKey(this ILogger logger, Guid keyId, DateTimeOffset expirationDate)
-        {
-            _consideringKeyWithExpirationDateAsDefaultKey(logger, keyId, expirationDate, null);
-        }
+        [LoggerMessage(13, LogLevel.Debug, "Considering key {KeyId:B} with expiration date {ExpirationDate:u} as default key.", EventName = "ConsideringKeyWithExpirationDateAsDefaultKey")]
+        public static partial void ConsideringKeyWithExpirationDateAsDefaultKey(this ILogger logger, Guid keyId, DateTimeOffset expirationDate);
 
-        public static void KeyIsNoLongerUnderConsiderationAsDefault(this ILogger logger, Guid keyId)
-        {
-            _keyIsNoLongerUnderConsiderationAsDefault(logger, keyId, null);
-        }
+        [LoggerMessage(14, LogLevel.Debug, "Key {KeyId:B} is no longer under consideration as default key because it is expired, revoked, or cannot be deciphered.", EventName = "KeyIsNoLongerUnderConsiderationAsDefault")]
+        public static partial void KeyIsNoLongerUnderConsiderationAsDefault(this ILogger logger, Guid keyId);
 
-        public static void UnknownElementWithNameFoundInKeyringSkipping(this ILogger logger, XName name)
-        {
-            _unknownElementWithNameFoundInKeyringSkipping(logger, name, null);
-        }
+        [LoggerMessage(15, LogLevel.Warning, "Unknown element with name '{Name}' found in keyring, skipping.", EventName = "UnknownElementWithNameFoundInKeyringSkipping")]
+        public static partial void UnknownElementWithNameFoundInKeyringSkipping(this ILogger logger, XName name);
 
-        public static void MarkedKeyAsRevokedInTheKeyring(this ILogger logger, Guid revokedKeyId)
-        {
-            _markedKeyAsRevokedInTheKeyring(logger, revokedKeyId, null);
-        }
+        [LoggerMessage(16, LogLevel.Debug, "Marked key {KeyId:B} as revoked in the keyring.", EventName = "MarkedKeyAsRevokedInTheKeyring")]
+        public static partial void MarkedKeyAsRevokedInTheKeyring(this ILogger logger, Guid keyId);
 
-        public static void TriedToProcessRevocationOfKeyButNoSuchKeyWasFound(this ILogger logger, Guid revokedKeyId)
-        {
-            _triedToProcessRevocationOfKeyButNoSuchKeyWasFound(logger, revokedKeyId, null);
-        }
+        [LoggerMessage(17, LogLevel.Warning, "Tried to process revocation of key {KeyId:B}, but no such key was found in keyring. Skipping.", EventName = "TriedToProcessRevocationOfKeyButNoSuchKeyWasFound")]
+        public static partial void TriedToProcessRevocationOfKeyButNoSuchKeyWasFound(this ILogger logger, Guid keyId);
 
-        public static void FoundKey(this ILogger logger, Guid keyId)
-        {
-            _foundKey(logger, keyId, null);
-        }
+        [LoggerMessage(18, LogLevel.Debug, "Found key {KeyId:B}.", EventName = "FoundKey")]
+        public static partial void FoundKey(this ILogger logger, Guid keyId);
 
-        public static void FoundRevocationOfAllKeysCreatedPriorTo(this ILogger logger, DateTimeOffset massRevocationDate)
-        {
-            _foundRevocationOfAllKeysCreatedPriorTo(logger, massRevocationDate, null);
-        }
+        [LoggerMessage(19, LogLevel.Debug, "Found revocation of all keys created prior to {RevocationDate:u}.", EventName = "FoundRevocationOfAllKeysCreatedPriorTo")]
+        public static partial void FoundRevocationOfAllKeysCreatedPriorTo(this ILogger logger, DateTimeOffset revocationDate);
 
-        public static void FoundRevocationOfKey(this ILogger logger, Guid keyId)
-        {
-            _foundRevocationOfKey(logger, keyId, null);
-        }
+        [LoggerMessage(20, LogLevel.Debug, "Found revocation of key {KeyId:B}.", EventName = "FoundRevocationOfKey")]
+        public static partial void FoundRevocationOfKey(this ILogger logger, Guid keyId);
 
-        public static void ExceptionWhileProcessingRevocationElement(this ILogger logger, XElement revocationElement, Exception exception)
-        {
-            _exceptionWhileProcessingRevocationElement(logger, revocationElement, exception);
-        }
+        [LoggerMessage(21, LogLevel.Error, "An exception occurred while processing the revocation element '{RevocationElement}'. Cannot continue keyring processing.", EventName = "ExceptionWhileProcessingRevocationElement")]
+        public static partial void ExceptionWhileProcessingRevocationElement(this ILogger logger, XElement revocationElement, Exception exception);
 
-        public static void RevokingAllKeysAsOfForReason(this ILogger logger, DateTimeOffset revocationDate, string? reason)
-        {
-            _revokingAllKeysAsOfForReason(logger, revocationDate, reason, null);
-        }
+        [LoggerMessage(22, LogLevel.Information, "Revoking all keys as of {RevocationDate:u} for reason '{Reason}'.", EventName = "RevokingAllKeysAsOfForReason")]
+        public static partial void RevokingAllKeysAsOfForReason(this ILogger logger, DateTimeOffset revocationDate, string? reason);
 
-        public static void KeyCacheExpirationTokenTriggeredByOperation(this ILogger logger, string opName)
-        {
-            _keyCacheExpirationTokenTriggeredByOperation(logger, opName, null);
-        }
+        [LoggerMessage(23, LogLevel.Debug, "Key cache expiration token triggered by '{OperationName}' operation.", EventName = "KeyCacheExpirationTokenTriggeredByOperation")]
+        public static partial void KeyCacheExpirationTokenTriggeredByOperation(this ILogger logger, string operationName);
 
-        public static void ExceptionWhileProcessingKeyElement(this ILogger logger, XElement keyElement, Exception exception)
-        {
-            _anExceptionOccurredWhileProcessingTheKeyElement(logger, keyElement, exception);
-        }
+        [LoggerMessage(24, LogLevel.Error, "An exception occurred while processing the key element '{Element}'.", EventName = "ExceptionOccurredWhileProcessingTheKeyElement")]
+        public static partial void ExceptionWhileProcessingKeyElement(this ILogger logger, XElement element, Exception exception);
 
-        public static void AnExceptionOccurredWhileProcessingElementDebug(this ILogger logger, XElement keyElement, Exception exception)
-        {
-            _anExceptionOccurredWhileProcessingTheKeyElementDebug(logger, keyElement, exception);
-        }
+        [LoggerMessage(25, LogLevel.Trace, "An exception occurred while processing the key element '{Element}'.", EventName = "ExceptionOccurredWhileProcessingTheKeyElementDebug")]
+        public static partial void AnExceptionOccurredWhileProcessingElementDebug(this ILogger logger, XElement element, Exception exception);
 
-        public static void EncryptingToWindowsDPAPIForCurrentUserAccount(this ILogger logger, string name)
-        {
-            _encryptingToWindowsDPAPIForCurrentUserAccount(logger, name, null);
-        }
+        [LoggerMessage(26, LogLevel.Debug, "Encrypting to Windows DPAPI for current user account ({Name}).", EventName = "EncryptingToWindowsDPAPIForCurrentUserAccount")]
+        public static partial void EncryptingToWindowsDPAPIForCurrentUserAccount(this ILogger logger, string name);
 
-        public static void AnErrorOccurredWhileEncryptingToX509CertificateWithThumbprint(this ILogger logger, string thumbprint, Exception exception)
-        {
-            _anErrorOccurredWhileEncryptingToX509CertificateWithThumbprint(logger, thumbprint, exception);
-        }
+        [LoggerMessage(28, LogLevel.Error, "An error occurred while encrypting to X.509 certificate with thumbprint '{Thumbprint}'.", EventName = "ErrorOccurredWhileEncryptingToX509CertificateWithThumbprint")]
+        public static partial void AnErrorOccurredWhileEncryptingToX509CertificateWithThumbprint(this ILogger logger, string thumbprint, Exception exception);
 
-        public static void EncryptingToX509CertificateWithThumbprint(this ILogger logger, string thumbprint)
-        {
-            _encryptingToX509CertificateWithThumbprint(logger, thumbprint, null);
-        }
+        [LoggerMessage(29, LogLevel.Debug, "Encrypting to X.509 certificate with thumbprint '{Thumbprint}'.", EventName = "EncryptingToX509CertificateWithThumbprint")]
+        public static partial void EncryptingToX509CertificateWithThumbprint(this ILogger logger, string thumbprint);
 
-        public static void ExceptionWhileTryingToResolveCertificateWithThumbprint(this ILogger logger, string thumbprint, Exception exception)
-        {
-            _exceptionOccurredWhileTryingToResolveCertificateWithThumbprint(logger, thumbprint, exception);
-        }
+        [LoggerMessage(30, LogLevel.Error, "An exception occurred while trying to resolve certificate with thumbprint '{Thumbprint}'.", EventName = "ExceptionOccurredWhileTryingToResolveCertificateWithThumbprint")]
+        public static partial void ExceptionWhileTryingToResolveCertificateWithThumbprint(this ILogger logger, string thumbprint, Exception exception);
 
-        public static void PerformingProtectOperationToKeyWithPurposes(this ILogger logger, Guid defaultKeyId, string p0)
-        {
-            _performingProtectOperationToKeyWithPurposes(logger, defaultKeyId, p0, null);
-        }
+        [LoggerMessage(31, LogLevel.Trace, "Performing protect operation to key {KeyId:B} with purposes {Purposes}.", EventName = "PerformingProtectOperationToKeyWithPurposes")]
+        public static partial void PerformingProtectOperationToKeyWithPurposes(this ILogger logger, Guid keyId, string purposes);
 
-        public static void DescriptorDeserializerTypeForKeyIs(this ILogger logger, Guid keyId, string assemblyQualifiedName)
-        {
-            _descriptorDeserializerTypeForKeyIs(logger, keyId, assemblyQualifiedName, null);
-        }
+        [LoggerMessage(32, LogLevel.Debug, "Descriptor deserializer type for key {KeyId:B} is '{AssemblyQualifiedName}'.", EventName = "DescriptorDeserializerTypeForKeyIs")]
+        public static partial void DescriptorDeserializerTypeForKeyIs(this ILogger logger, Guid keyId, string assemblyQualifiedName);
 
-        public static void KeyEscrowSinkFoundWritingKeyToEscrow(this ILogger logger, Guid keyId)
-        {
-            _keyEscrowSinkFoundWritingKeyToEscrow(logger, keyId, null);
-        }
+        [LoggerMessage(33, LogLevel.Debug, "Key escrow sink found. Writing key {KeyId:B} to escrow.", EventName = "KeyEscrowSinkFoundWritingKeyToEscrow")]
+        public static partial void KeyEscrowSinkFoundWritingKeyToEscrow(this ILogger logger, Guid keyId);
 
-        public static void NoKeyEscrowSinkFoundNotWritingKeyToEscrow(this ILogger logger, Guid keyId)
-        {
-            _noKeyEscrowSinkFoundNotWritingKeyToEscrow(logger, keyId, null);
-        }
+        [LoggerMessage(34, LogLevel.Debug, "No key escrow sink found. Not writing key {KeyId:B} to escrow.", EventName = "NoKeyEscrowSinkFoundNotWritingKeyToEscrow")]
+        public static partial void NoKeyEscrowSinkFoundNotWritingKeyToEscrow(this ILogger logger, Guid keyId);
 
-        public static void NoXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm(this ILogger logger, Guid keyId)
-        {
-            _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm(logger, keyId, null);
-        }
+        [LoggerMessage(35, LogLevel.Warning, "No XML encryptor configured. Key {KeyId:B} may be persisted to storage in unencrypted form.", EventName = "NoXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm")]
+        public static partial void NoXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm(this ILogger logger, Guid keyId);
 
-        public static void RevokingKeyForReason(this ILogger logger, Guid keyId, DateTimeOffset revocationDate, string? reason)
-        {
-            _revokingKeyForReason(logger, keyId, revocationDate, reason, null);
-        }
+        [LoggerMessage(36, LogLevel.Information, "Revoking key {KeyId:B} at {RevocationDate:u} for reason '{Reason}'.", EventName = "RevokingKeyForReason")]
+        public static partial void RevokingKeyForReason(this ILogger logger, Guid keyId, DateTimeOffset revocationDate, string? reason);
 
-        public static void ReadingDataFromFile(this ILogger logger, string fullPath)
-        {
-            _readingDataFromFile(logger, fullPath, null);
-        }
+        [LoggerMessage(37, LogLevel.Debug, "Reading data from file '{FullPath}'.", EventName = "ReadingDataFromFile")]
+        public static partial void ReadingDataFromFile(this ILogger logger, string fullPath);
 
-        public static void NameIsNotSafeFileName(this ILogger logger, string friendlyName, string newFriendlyName)
-        {
-            _nameIsNotSafeFileName(logger, friendlyName, newFriendlyName, null);
-        }
+        [LoggerMessage(38, LogLevel.Debug, "The name '{FriendlyName}' is not a safe file name, using '{NewFriendlyName}' instead.", EventName = "NameIsNotSafeFileName")]
+        public static partial void NameIsNotSafeFileName(this ILogger logger, string friendlyName, string newFriendlyName);
 
-        public static void WritingDataToFile(this ILogger logger, string finalFilename)
-        {
-            _writingDataToFile(logger, finalFilename, null);
-        }
+        [LoggerMessage(39, LogLevel.Information, "Writing data to file '{FileName}'.", EventName = "WritingDataToFile")]
+        public static partial void WritingDataToFile(this ILogger logger, string fileName);
 
-        [SupportedOSPlatform("windows")]
-        public static void ReadingDataFromRegistryKeyValue(this ILogger logger, RegistryKey regKey, string valueName)
-        {
-            if (_readingDataFromRegistryKeyValue != null)
-            {
-                _readingDataFromRegistryKeyValue(logger, regKey, valueName, null);
-            }
-        }
+        [LoggerMessage(40, LogLevel.Debug, "Reading data from registry key '{RegistryKeyName}', value '{Value}'.", EventName = "ReadingDataFromRegistryKeyValue")]
+        public static partial void ReadingDataFromRegistryKeyValue(this ILogger logger, RegistryKey registryKeyName, string value);
 
-        public static void NameIsNotSafeRegistryValueName(this ILogger logger, string friendlyName, string newFriendlyName)
-        {
-            _nameIsNotSafeRegistryValueName(logger, friendlyName, newFriendlyName, null);
-        }
+        [LoggerMessage(41, LogLevel.Debug, "The name '{FriendlyName}' is not a safe registry value name, using '{NewFriendlyName}' instead.", EventName = "NameIsNotSafeRegistryValueName")]
+        public static partial void NameIsNotSafeRegistryValueName(this ILogger logger, string friendlyName, string newFriendlyName);
 
-        public static void DecryptingSecretElementUsingWindowsDPAPING(this ILogger logger, string? protectionDescriptorRule)
-        {
-            _decryptingSecretElementUsingWindowsDPAPING(logger, protectionDescriptorRule, null);
-        }
+        [LoggerMessage(42, LogLevel.Debug, "Decrypting secret element using Windows DPAPI-NG with protection descriptor rule '{DescriptorRule}'.", EventName = "DecryptingSecretElementUsingWindowsDPAPING")]
+        public static partial void DecryptingSecretElementUsingWindowsDPAPING(this ILogger logger, string? descriptorRule);
 
-        public static void EncryptingToWindowsDPAPINGUsingProtectionDescriptorRule(this ILogger logger, string protectionDescriptorRuleString)
-        {
-            _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule(logger, protectionDescriptorRuleString, null);
-        }
+        [LoggerMessage(27, LogLevel.Debug, "Encrypting to Windows DPAPI-NG using protection descriptor rule '{DescriptorRule}'.", EventName = "EncryptingToWindowsDPAPINGUsingProtectionDescriptorRule")]
+        public static partial void EncryptingToWindowsDPAPINGUsingProtectionDescriptorRule(this ILogger logger, string descriptorRule);
 
-        public static void ExceptionOccurredTryingToDecryptElement(this ILogger logger, Exception exception)
-        {
-            _exceptionOccurredTryingToDecryptElement(logger, exception);
-        }
+        [LoggerMessage(43, LogLevel.Error, "An exception occurred while trying to decrypt the element.", EventName = "ExceptionOccurredTryingToDecryptElement")]
+        public static partial void ExceptionOccurredTryingToDecryptElement(this ILogger logger, Exception exception);
 
-        public static void EncryptingUsingNullEncryptor(this ILogger logger)
-        {
-            _encryptingUsingNullEncryptor(logger, null);
-        }
+        [LoggerMessage(44, LogLevel.Warning, "Encrypting using a null encryptor; secret information isn't being protected.", EventName = "EncryptingUsingNullEncryptor")]
+        public static partial void EncryptingUsingNullEncryptor(this ILogger logger);
 
-        public static void UsingEphemeralDataProtectionProvider(this ILogger logger)
-        {
-            _usingEphemeralDataProtectionProvider(logger, null);
-        }
+        [LoggerMessage(45, LogLevel.Information, "Using ephemeral data protection provider. Payloads will be undecipherable upon application shutdown.", EventName = "UsingEphemeralDataProtectionProvider")]
+        public static partial void UsingEphemeralDataProtectionProvider(this ILogger logger);
 
-        public static void ExistingCachedKeyRingIsExpired(this ILogger logger)
-        {
-            _existingCachedKeyRingIsExpiredRefreshing(logger, null);
-        }
+        [LoggerMessage(46, LogLevel.Debug, "Existing cached key ring is expired. Refreshing.", EventName = "ExistingCachedKeyRingIsExpiredRefreshing")]
+        public static partial void ExistingCachedKeyRingIsExpired(this ILogger logger);
 
-        public static void ErrorOccurredWhileRefreshingKeyRing(this ILogger logger, Exception exception)
-        {
-            _errorOccurredWhileRefreshingKeyRing(logger, exception);
-        }
+        [LoggerMessage(47, LogLevel.Error, "An error occurred while refreshing the key ring. Will try again in 2 minutes.", EventName = "ErrorOccurredWhileRefreshingKeyRing")]
+        public static partial void ErrorOccurredWhileRefreshingKeyRing(this ILogger logger, Exception exception);
 
-        public static void ErrorOccurredWhileReadingKeyRing(this ILogger logger, Exception exception)
-        {
-            _errorOccurredWhileReadingKeyRing(logger, exception);
-        }
+        [LoggerMessage(48, LogLevel.Error, "An error occurred while reading the key ring.", EventName = "ErrorOccurredWhileReadingKeyRing")]
+        public static partial void ErrorOccurredWhileReadingKeyRing(this ILogger logger, Exception exception);
 
-        public static void KeyRingDoesNotContainValidDefaultKey(this ILogger logger)
-        {
-            _keyRingDoesNotContainValidDefaultKey(logger, null);
-        }
+        [LoggerMessage(49, LogLevel.Error, "The key ring does not contain a valid default key, and the key manager is configured with auto-generation of keys disabled.", EventName = "KeyRingDoesNotContainValidDefaultKey")]
+        public static partial void KeyRingDoesNotContainValidDefaultKey(this ILogger logger);
 
-        public static void UsingInmemoryRepository(this ILogger logger)
-        {
-            _usingInmemoryRepository(logger, null);
-        }
+        [LoggerMessage(50, LogLevel.Warning, "Using an in-memory repository. Keys will not be persisted to storage.", EventName = "UsingInMemoryRepository")]
+        public static partial void UsingInmemoryRepository(this ILogger logger);
 
-        public static void DecryptingSecretElementUsingWindowsDPAPI(this ILogger logger)
-        {
-            _decryptingSecretElementUsingWindowsDPAPI(logger, null);
-        }
+        [LoggerMessage(51, LogLevel.Debug, "Decrypting secret element using Windows DPAPI.", EventName = "DecryptingSecretElementUsingWindowsDPAPI")]
+        public static partial void DecryptingSecretElementUsingWindowsDPAPI(this ILogger logger);
 
-        public static void DefaultKeyExpirationImminentAndRepository(this ILogger logger)
-        {
-            _defaultKeyExpirationImminentAndRepository(logger, null);
-        }
+        [LoggerMessage(52, LogLevel.Debug, "Default key expiration imminent and repository contains no viable successor. Caller should generate a successor.", EventName = "DefaultKeyExpirationImminentAndRepository")]
+        public static partial void DefaultKeyExpirationImminentAndRepository(this ILogger logger);
 
-        public static void RepositoryContainsNoViableDefaultKey(this ILogger logger)
-        {
-            _repositoryContainsNoViableDefaultKey(logger, null);
-        }
+        [LoggerMessage(53, LogLevel.Debug, "Repository contains no viable default key. Caller should generate a key with immediate activation.", EventName = "RepositoryContainsNoViableDefaultKey")]
+        public static partial void RepositoryContainsNoViableDefaultKey(this ILogger logger);
 
-        public static void ErrorOccurredWhileEncryptingToWindowsDPAPI(this ILogger logger, Exception exception)
-        {
-            _errorOccurredWhileEncryptingToWindowsDPAPI(logger, exception);
-        }
+        [LoggerMessage(54, LogLevel.Error, "An error occurred while encrypting to Windows DPAPI.", EventName = "ErrorOccurredWhileEncryptingToWindowsDPAPI")]
+        public static partial void ErrorOccurredWhileEncryptingToWindowsDPAPI(this ILogger logger, Exception exception);
 
-        public static void EncryptingToWindowsDPAPIForLocalMachineAccount(this ILogger logger)
-        {
-            _encryptingToWindowsDPAPIForLocalMachineAccount(logger, null);
-        }
+        [LoggerMessage(55, LogLevel.Debug, "Encrypting to Windows DPAPI for local machine account.", EventName = "EncryptingToWindowsDPAPIForLocalMachineAccount")]
+        public static partial void EncryptingToWindowsDPAPIForLocalMachineAccount(this ILogger logger);
 
-        public static void ErrorOccurredWhileEncryptingToWindowsDPAPING(this ILogger logger, Exception exception)
-        {
-            _errorOccurredWhileEncryptingToWindowsDPAPING(logger, exception);
-        }
+        [LoggerMessage(56, LogLevel.Error, "An error occurred while encrypting to Windows DPAPI-NG.", EventName = "ErrorOccurredWhileEncryptingToWindowsDPAPING")]
+        public static partial void ErrorOccurredWhileEncryptingToWindowsDPAPING(this ILogger logger, Exception exception);
 
-        public static void PolicyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing(this ILogger logger)
-        {
-            _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing(logger, null);
-        }
+        [LoggerMessage(57, LogLevel.Debug, "Policy resolution states that a new key should be added to the key ring.", EventName = "PolicyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing")]
+        public static partial void PolicyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing(this ILogger logger);
 
-        public static void CreatingKey(this ILogger logger, Guid keyId, DateTimeOffset creationDate, DateTimeOffset activationDate, DateTimeOffset expirationDate)
-        {
-            _creatingKey(logger, keyId, creationDate, activationDate, expirationDate, null);
-        }
+        [LoggerMessage(58, LogLevel.Information, "Creating key {KeyId:B} with creation date {CreationDate:u}, activation date {ActivationDate:u}, and expiration date {ExpirationDate:u}.", EventName = "CreatingKey")]
+        public static partial void CreatingKey(this ILogger logger, Guid keyId, DateTimeOffset creationDate, DateTimeOffset activationDate, DateTimeOffset expirationDate);
 
-        public static void UsingEphemeralKeyRepository(this ILogger logger)
-        {
-            _usingEphemeralKeyRepository(logger, null);
-        }
+        [LoggerMessage(59, LogLevel.Warning, "Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.", EventName = "UsingEphemeralKeyRepository")]
+        public static partial void UsingEphemeralKeyRepository(this ILogger logger);
 
-        public static void UsingRegistryAsKeyRepositoryWithDPAPI(this ILogger logger, string name)
-        {
-            _usingRegistryAsKeyRepositoryWithDPAPI(logger, name, null);
-        }
+        [LoggerMessage(61, LogLevel.Information, "User profile not available. Using '{Name}' as key repository and Windows DPAPI to encrypt keys at rest.", EventName = "UsingRegistryAsKeyRepositoryWithDPAPI")]
+        public static partial void UsingRegistryAsKeyRepositoryWithDPAPI(this ILogger logger, string name);
 
-        public static void UsingProfileAsKeyRepository(this ILogger logger, string fullName)
-        {
-            _usingProfileAsKeyRepository(logger, fullName, null);
-        }
+        [LoggerMessage(62, LogLevel.Information, "User profile is available. Using '{FullName}' as key repository; keys will not be encrypted at rest.", EventName = "UsingProfileAsKeyRepository")]
+        public static partial void UsingProfileAsKeyRepository(this ILogger logger, string fullName);
 
-        public static void UsingProfileAsKeyRepositoryWithDPAPI(this ILogger logger, string fullName)
-        {
-            _usingProfileAsKeyRepositoryWithDPAPI(logger, fullName, null);
-        }
+        [LoggerMessage(63, LogLevel.Information, "User profile is available. Using '{FullName}' as key repository and Windows DPAPI to encrypt keys at rest.", EventName = "UsingProfileAsKeyRepositoryWithDPAPI")]
+        public static partial void UsingProfileAsKeyRepositoryWithDPAPI(this ILogger logger, string fullName);
 
-        public static void UsingAzureAsKeyRepository(this ILogger logger, string fullName)
-        {
-            _usingAzureAsKeyRepository(logger, fullName, null);
-        }
+        [LoggerMessage(64, LogLevel.Information, "Azure Web Sites environment detected. Using '{FullName}' as key repository; keys will not be encrypted at rest.", EventName = "UsingAzureAsKeyRepository")]
+        public static partial void UsingAzureAsKeyRepository(this ILogger logger, string fullName);
 
-        public static void KeyRingWasLoadedOnStartup(this ILogger logger, Guid defaultKeyId)
-        {
-            _keyRingWasLoadedOnStartup(logger, defaultKeyId, null);
-        }
+        [LoggerMessage(65, LogLevel.Debug, "Key ring with default key {KeyId:B} was loaded during application startup.", EventName = "KeyRingWasLoadedOnStartup")]
+        public static partial void KeyRingWasLoadedOnStartup(this ILogger logger, Guid keyId);
 
-        public static void KeyRingFailedToLoadOnStartup(this ILogger logger, Exception innerException)
-        {
-            _keyRingFailedToLoadOnStartup(logger, innerException);
-        }
+        [LoggerMessage(66, LogLevel.Information, "Key ring failed to load during application startup.", EventName = "KeyRingFailedToLoadOnStartup")]
+        public static partial void KeyRingFailedToLoadOnStartup(this ILogger logger, Exception innerException);
 
-        public static void UsingEphemeralFileSystemLocationInContainer(this ILogger logger, string path)
-        {
-            _usingEphemeralFileSystemLocationInContainer(logger, path, null);
-        }
+        [LoggerMessage(60, LogLevel.Warning, "Storing keys in a directory '{path}' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.", EventName = "UsingEphemeralFileSystemLocationInContainer")]
+        public static partial void UsingEphemeralFileSystemLocationInContainer(this ILogger logger, string path);
     }
 }

+ 5 - 22
src/DataProtection/EntityFrameworkCore/src/LoggingExtensions.cs

@@ -1,31 +1,14 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
-
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, string?, string?, Exception?> _readingXmlFromKey;
-        private static readonly Action<ILogger, string, string, Exception?> _savingKeyToDbContext;
-
-        static LoggingExtensions()
-        {
-            _readingXmlFromKey = LoggerMessage.Define<string?, string?>(
-                eventId: new EventId(1, "ReadKeyFromElement"),
-                logLevel: LogLevel.Debug,
-                formatString: "Reading data with key '{FriendlyName}', value '{Value}'.");
-            _savingKeyToDbContext = LoggerMessage.Define<string, string>(
-                eventId: new EventId(2, "SavingKeyToDbContext"),
-                logLevel: LogLevel.Debug,
-                formatString: "Saving key '{FriendlyName}' to '{DbContext}'.");
-        }
-
-        public static void ReadingXmlFromKey(this ILogger logger, string? friendlyName, string? keyXml)
-            => _readingXmlFromKey(logger, friendlyName, keyXml, null);
+        [LoggerMessage(1, LogLevel.Debug, "Reading data with key '{FriendlyName}', value '{Value}'.", EventName = "ReadKeyFromElement")]
+        public static partial void ReadingXmlFromKey(this ILogger logger, string? friendlyName, string? value);
 
-        public static void LogSavingKeyToDbContext(this ILogger logger, string friendlyName, string contextName)
-            => _savingKeyToDbContext(logger, friendlyName, contextName, null);
+        [LoggerMessage(2, LogLevel.Debug, "Saving key '{FriendlyName}' to '{DbContext}'.", EventName = "SavingKeyToDbContext")]
+        public static partial void LogSavingKeyToDbContext(this ILogger logger, string friendlyName, string dbContext);
     }
 }

+ 23 - 115
src/Middleware/CORS/src/CORSLoggerExtensions.cs

@@ -6,131 +6,39 @@ using Microsoft.Extensions.Logging;
 
 namespace Microsoft.AspNetCore.Cors
 {
-    internal static class CORSLoggerExtensions
+    internal static partial class CORSLoggerExtensions
     {
-        private static readonly Action<ILogger, Exception?> _isPreflightRequest;
-        private static readonly Action<ILogger, string, Exception?> _requestHasOriginHeader;
-        private static readonly Action<ILogger, Exception?> _requestDoesNotHaveOriginHeader;
-        private static readonly Action<ILogger, Exception?> _policySuccess;
-        private static readonly Action<ILogger, Exception?> _policyFailure;
-        private static readonly Action<ILogger, string, Exception?> _originNotAllowed;
-        private static readonly Action<ILogger, string, Exception?> _accessControlMethodNotAllowed;
-        private static readonly Action<ILogger, string, Exception?> _requestHeaderNotAllowed;
-        private static readonly Action<ILogger, Exception?> _failedToSetCorsHeaders;
-        private static readonly Action<ILogger, Exception?> _noCorsPolicyFound;
-        private static readonly Action<ILogger, Exception?> _isNotPreflightRequest;
+        [LoggerMessage(1, LogLevel.Debug, "The request is a preflight request.", EventName = "IsPreflightRequest")]
+        public static partial void IsPreflightRequest(this ILogger logger);
 
-        static CORSLoggerExtensions()
-        {
-            _isPreflightRequest = LoggerMessage.Define(
-                LogLevel.Debug,
-                new EventId(1, "IsPreflightRequest"),
-                "The request is a preflight request.");
+        [LoggerMessage(2, LogLevel.Debug, "The request has an origin header: '{origin}'.", EventName = "RequestHasOriginHeader")]
+        public static partial void RequestHasOriginHeader(this ILogger logger, string origin);
 
-            _requestHasOriginHeader = LoggerMessage.Define<string>(
-                LogLevel.Debug,
-                new EventId(2, "RequestHasOriginHeader"),
-                "The request has an origin header: '{origin}'.");
+        [LoggerMessage(3, LogLevel.Debug, "The request does not have an origin header.", EventName = "RequestDoesNotHaveOriginHeader")]
+        public static partial void RequestDoesNotHaveOriginHeader(this ILogger logger);
 
-            _requestDoesNotHaveOriginHeader = LoggerMessage.Define(
-                LogLevel.Debug,
-                new EventId(3, "RequestDoesNotHaveOriginHeader"),
-                "The request does not have an origin header.");
+        [LoggerMessage(4, LogLevel.Information, "CORS policy execution successful.", EventName = "PolicySuccess")]
+        public static partial void PolicySuccess(this ILogger logger);
 
-            _policySuccess = LoggerMessage.Define(
-                LogLevel.Information,
-                new EventId(4, "PolicySuccess"),
-                "CORS policy execution successful.");
+        [LoggerMessage(5, LogLevel.Information, "CORS policy execution failed.", EventName = "PolicyFailure")]
+        public static partial void PolicyFailure(this ILogger logger);
 
-            _policyFailure = LoggerMessage.Define(
-                LogLevel.Information,
-                new EventId(5, "PolicyFailure"),
-                "CORS policy execution failed.");
+        [LoggerMessage(6, LogLevel.Information, "Request origin {origin} does not have permission to access the resource.", EventName = "OriginNotAllowed")]
+        public static partial void OriginNotAllowed(this ILogger logger, string origin);
 
-            _originNotAllowed = LoggerMessage.Define<string>(
-                LogLevel.Information,
-                new EventId(6, "OriginNotAllowed"),
-                "Request origin {origin} does not have permission to access the resource.");
+        [LoggerMessage(7, LogLevel.Information, "Request method {accessControlRequestMethod} not allowed in CORS policy.", EventName = "AccessControlMethodNotAllowed")]
+        public static partial void AccessControlMethodNotAllowed(this ILogger logger, string accessControlRequestMethod);
 
-            _accessControlMethodNotAllowed = LoggerMessage.Define<string>(
-                LogLevel.Information,
-                new EventId(7, "AccessControlMethodNotAllowed"),
-                "Request method {accessControlRequestMethod} not allowed in CORS policy.");
+        [LoggerMessage(8, LogLevel.Information, "Request header '{requestHeader}' not allowed in CORS policy.", EventName = "RequestHeaderNotAllowed")]
+        public static partial void RequestHeaderNotAllowed(this ILogger logger, string requestHeader);
 
-            _requestHeaderNotAllowed = LoggerMessage.Define<string>(
-                LogLevel.Information,
-                new EventId(8, "RequestHeaderNotAllowed"),
-                "Request header '{requestHeader}' not allowed in CORS policy.");
+        [LoggerMessage(9, LogLevel.Warning, "Failed to apply CORS Response headers.", EventName = "FailedToSetCorsHeaders")]
+        public static partial void FailedToSetCorsHeaders(this ILogger logger, Exception? exception);
 
-            _failedToSetCorsHeaders = LoggerMessage.Define(
-                LogLevel.Warning,
-                new EventId(9, "FailedToSetCorsHeaders"),
-                "Failed to apply CORS Response headers.");
+        [LoggerMessage(10, LogLevel.Information, "No CORS policy found for the specified request.", EventName = "NoCorsPolicyFound")]
+        public static partial void NoCorsPolicyFound(this ILogger logger);
 
-            _noCorsPolicyFound = LoggerMessage.Define(
-                LogLevel.Information,
-                new EventId(10, "NoCorsPolicyFound"),
-                "No CORS policy found for the specified request.");
-
-            _isNotPreflightRequest = LoggerMessage.Define(
-                LogLevel.Debug,
-                new EventId(12, "IsNotPreflightRequest"),
-                "This request uses the HTTP OPTIONS method but does not have an Access-Control-Request-Method header. This request will not be treated as a CORS preflight request.");
-        }
-
-        public static void IsPreflightRequest(this ILogger logger)
-        {
-            _isPreflightRequest(logger, null);
-        }
-
-        public static void RequestHasOriginHeader(this ILogger logger, string origin)
-        {
-            _requestHasOriginHeader(logger, origin, null);
-        }
-
-        public static void RequestDoesNotHaveOriginHeader(this ILogger logger)
-        {
-            _requestDoesNotHaveOriginHeader(logger, null);
-        }
-
-        public static void PolicySuccess(this ILogger logger)
-        {
-            _policySuccess(logger, null);
-        }
-
-        public static void PolicyFailure(this ILogger logger)
-        {
-            _policyFailure(logger, null);
-        }
-
-        public static void OriginNotAllowed(this ILogger logger, string origin)
-        {
-            _originNotAllowed(logger, origin, null);
-        }
-
-        public static void AccessControlMethodNotAllowed(this ILogger logger, string accessControlMethod)
-        {
-            _accessControlMethodNotAllowed(logger, accessControlMethod, null);
-        }
-
-        public static void RequestHeaderNotAllowed(this ILogger logger, string requestHeader)
-        {
-            _requestHeaderNotAllowed(logger, requestHeader, null);
-        }
-
-        public static void FailedToSetCorsHeaders(this ILogger logger, Exception? exception)
-        {
-            _failedToSetCorsHeaders(logger, exception);
-        }
-
-        public static void NoCorsPolicyFound(this ILogger logger)
-        {
-            _noCorsPolicyFound(logger, null);
-        }
-
-        public static void IsNotPreflightRequest(this ILogger logger)
-        {
-            _isNotPreflightRequest(logger, null);
-        }
+        [LoggerMessage(12, LogLevel.Debug, "This request uses the HTTP OPTIONS method but does not have an Access-Control-Request-Method header. This request will not be treated as a CORS preflight request.", EventName = "IsNotPreflightRequest")]
+        public static partial void IsNotPreflightRequest(this ILogger logger);
     }
 }

+ 10 - 32
src/Middleware/ConcurrencyLimiter/src/ConcurrencyLimiterMiddleware.cs

@@ -1,8 +1,6 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
-using System.Threading.Tasks;
 using Microsoft.AspNetCore.Http;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Options;
@@ -12,7 +10,7 @@ namespace Microsoft.AspNetCore.ConcurrencyLimiter
     /// <summary>
     /// Limits the number of concurrent requests allowed in the application.
     /// </summary>
-    public class ConcurrencyLimiterMiddleware
+    public partial class ConcurrencyLimiterMiddleware
     {
         private readonly IQueuePolicy _queuePolicy;
         private readonly RequestDelegate _next;
@@ -84,39 +82,19 @@ namespace Microsoft.AspNetCore.ConcurrencyLimiter
             }
         }
 
-        private static class ConcurrencyLimiterLog
+        private static partial class ConcurrencyLimiterLog
         {
-            private static readonly Action<ILogger, int, Exception?> _requestEnqueued =
-                LoggerMessage.Define<int>(LogLevel.Debug, new EventId(1, "RequestEnqueued"), "MaxConcurrentRequests limit reached, request has been queued. Current active requests: {ActiveRequests}.");
+            [LoggerMessage(1, LogLevel.Debug, "MaxConcurrentRequests limit reached, request has been queued. Current active requests: {ActiveRequests}.", EventName = "RequestEnqueued")]
+            internal static partial void RequestEnqueued(ILogger logger, int activeRequests);
 
-            private static readonly Action<ILogger, int, Exception?> _requestDequeued =
-                LoggerMessage.Define<int>(LogLevel.Debug, new EventId(2, "RequestDequeued"), "Request dequeued. Current active requests: {ActiveRequests}.");
+            [LoggerMessage(2, LogLevel.Debug, "Request dequeued. Current active requests: {ActiveRequests}.", EventName = "RequestDequeued")]
+            internal static partial void RequestDequeued(ILogger logger, int activeRequests);
 
-            private static readonly Action<ILogger, int, Exception?> _requestRunImmediately =
-                LoggerMessage.Define<int>(LogLevel.Debug, new EventId(3, "RequestRunImmediately"), "Below MaxConcurrentRequests limit, running request immediately. Current active requests: {ActiveRequests}");
+            [LoggerMessage(3, LogLevel.Debug, "Below MaxConcurrentRequests limit, running request immediately. Current active requests: {ActiveRequests}", EventName = "RequestRunImmediately")]
+            internal static partial void RequestRunImmediately(ILogger logger, int activeRequests);
 
-            private static readonly Action<ILogger, Exception?> _requestRejectedQueueFull =
-                LoggerMessage.Define(LogLevel.Debug, new EventId(4, "RequestRejectedQueueFull"), "Currently at the 'RequestQueueLimit', rejecting this request with a '503 server not available' error");
-
-            internal static void RequestEnqueued(ILogger logger, int activeRequests)
-            {
-                _requestEnqueued(logger, activeRequests, null);
-            }
-
-            internal static void RequestDequeued(ILogger logger, int activeRequests)
-            {
-                _requestDequeued(logger, activeRequests, null);
-            }
-
-            internal static void RequestRunImmediately(ILogger logger, int activeRequests)
-            {
-                _requestRunImmediately(logger, activeRequests, null);
-            }
-
-            internal static void RequestRejectedQueueFull(ILogger logger)
-            {
-                _requestRejectedQueueFull(logger, null);
-            }
+            [LoggerMessage(4, LogLevel.Debug, "Currently at the 'RequestQueueLimit', rejecting this request with a '503 server not available' error", EventName = "RequestRejectedQueueFull")]
+            internal static partial void RequestRejectedQueueFull(ILogger logger);
         }
     }
 }

+ 35 - 129
src/Middleware/Diagnostics.EntityFrameworkCore/src/DiagnosticsEntityFrameworkCoreLoggerExtensions.cs

@@ -1,152 +1,58 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
 using Microsoft.Extensions.Logging;
 
 namespace Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
 {
-    internal static class DiagnosticsEntityFrameworkCoreLoggerExtensions
+    internal static partial class MigrationsEndPointMiddlewareLoggerExtensions
     {
-        // MigrationsEndPointMiddleware
-        private static readonly Action<ILogger, Exception?> _noContextType = LoggerMessage.Define(
-            LogLevel.Error,
-            new EventId(1, "NoContextType"),
-            "No context type was specified. Ensure the form data from the request includes a 'context' value, specifying the context type name to apply migrations for.");
+        [LoggerMessage(1, LogLevel.Error, "No context type was specified. Ensure the form data from the request includes a 'context' value, specifying the context type name to apply migrations for.", EventName = "NoContextType")]
+        public static partial void NoContextType(this ILogger logger);
 
-        private static readonly Action<ILogger, string, Exception?> _contextNotRegistered = LoggerMessage.Define<string>(
-            LogLevel.Error,
-            new EventId(3, "ContextNotRegistered"),
-            "The context type '{ContextTypeName}' was not found in services. This usually means the context was not registered in services during startup. You probably want to call AddScoped<>() inside the UseServices(...) call in your application startup code.");
+        [LoggerMessage(3, LogLevel.Error, "The context type '{ContextTypeName}' was not found in services. This usually means the context was not registered in services during startup. You probably want to call AddScoped<>() inside the UseServices(...) call in your application startup code.", EventName = "ContextNotRegistered")]
+        public static partial void ContextNotRegistered(this ILogger logger, string contextTypeName);
 
-        private static readonly Action<ILogger, string, Exception?> _requestPathMatched = LoggerMessage.Define<string>(
-            LogLevel.Debug,
-            new EventId(4, "RequestPathMatched"),
-            "Request path matched the path configured for this migrations endpoint({RequestPath}). Attempting to process the migrations request.");
+        [LoggerMessage(4, LogLevel.Debug, "Request path matched the path configured for this migrations endpoint({RequestPath}). Attempting to process the migrations request.", EventName = "RequestPathMatched")]
+        public static partial void RequestPathMatched(this ILogger logger, string requestPath);
 
-        private static readonly Action<ILogger, string, Exception?> _applyingMigrations = LoggerMessage.Define<string>(
-            LogLevel.Debug,
-            new EventId(5, "ApplyingMigrations"),
-            "Request is valid, applying migrations for context '{ContextTypeName}'");
+        [LoggerMessage(5, LogLevel.Debug, "Request is valid, applying migrations for context '{ContextTypeName}'", EventName = "ApplyingMigrations")]
+        public static partial void ApplyingMigrations(this ILogger logger, string contextTypeName);
 
-        private static readonly Action<ILogger, string, Exception?> _migrationsApplied = LoggerMessage.Define<string>(
-            LogLevel.Debug,
-            new EventId(6, "MigrationsApplied"),
-            "Migrations successfully applied for context '{ContextTypeName}'.");
+        [LoggerMessage(6, LogLevel.Debug, "Migrations successfully applied for context '{ContextTypeName}'.", EventName = "MigrationsApplied")]
+        public static partial void MigrationsApplied(this ILogger logger, string contextTypeName);
 
-        private static readonly Action<ILogger, string, Exception> _migrationsEndPointMiddlewareException = LoggerMessage.Define<string>(
-            LogLevel.Error,
-            new EventId(7, "MigrationsEndPointException"),
-            "An error occurred while applying the migrations for '{ContextTypeName}'. See InnerException for details:");
-
-        // DatabaseErrorPageMiddleware
-        private static readonly Action<ILogger, Type, Exception?> _attemptingToMatchException = LoggerMessage.Define<Type>(
-            LogLevel.Debug,
-            new EventId(1, "AttemptingToMatchException"),
-            "{ExceptionType} occurred, checking if Entity Framework recorded this exception as resulting from a failed database operation.");
-
-        private static readonly Action<ILogger, Exception?> _noRecordedException = LoggerMessage.Define(
-            LogLevel.Debug,
-            new EventId(2, "NoRecordedException"),
-            "Entity Framework did not record any exceptions due to failed database operations. This means the current exception is not a failed Entity Framework database operation, or the current exception occurred from a DbContext that was not obtained from request services.");
-
-        private static readonly Action<ILogger, Exception?> _noMatch = LoggerMessage.Define(
-            LogLevel.Debug,
-            new EventId(3, "NoMatchFound"),
-            "The current exception (and its inner exceptions) do not match the last exception Entity Framework recorded due to a failed database operation. This means the database operation exception was handled and another exception occurred later in the request.");
-
-        private static readonly Action<ILogger, Exception?> _matched = LoggerMessage.Define(
-            LogLevel.Debug,
-            new EventId(4, "MatchFound"),
-            "Entity Framework recorded that the current exception was due to a failed database operation. Attempting to show database error page.");
-
-        private static readonly Action<ILogger, string, Exception?> _contextNotRegisteredDatabaseErrorPageMiddleware = LoggerMessage.Define<string>(
-            LogLevel.Error,
-            new EventId(5, "ContextNotRegistered"),
-            "The context type '{ContextTypeName}' was not found in services. This usually means the context was not registered in services during startup. You probably want to call AddScoped<>() inside the UseServices(...) call in your application startup code. Skipping display of the database error page.");
-
-        private static readonly Action<ILogger, Exception?> _notRelationalDatabase = LoggerMessage.Define(
-            LogLevel.Debug,
-            new EventId(6, "NotRelationalDatabase"),
-            "The target data store is not a relational database. Skipping the database error page.");
-
-        private static readonly Action<ILogger, Exception> _databaseErrorPageMiddlewareException = LoggerMessage.Define(
-            LogLevel.Error,
-            new EventId(7, "DatabaseErrorPageException"),
-            "An exception occurred while calculating the database error page content. Skipping display of the database error page.");
-
-        // DatabaseDeveloperPageExceptionFilter
-        private static readonly Action<ILogger, Exception?> _responseStartedDatabaseDeveloperPageExceptionFilter =
-            LoggerMessage.Define(LogLevel.Warning, new EventId(1, "ResponseStarted"), "The response has already started, the next developer page exception filter will not be executed.");
-
-        public static void NoContextType(this ILogger logger)
-        {
-            _noContextType(logger, null);
-        }
-
-        public static void ContextNotRegistered(this ILogger logger, string contextTypeName)
-        {
-            _contextNotRegistered(logger, contextTypeName, null);
-        }
-
-        public static void RequestPathMatched(this ILogger logger, string requestPath)
-        {
-            _requestPathMatched(logger, requestPath, null);
-        }
-
-        public static void ApplyingMigrations(this ILogger logger, string contextTypeName)
-        {
-            _applyingMigrations(logger, contextTypeName, null);
-        }
-
-        public static void MigrationsApplied(this ILogger logger, string contextTypeName)
-        {
-            _migrationsApplied(logger, contextTypeName, null);
-        }
-
-        public static void MigrationsEndPointMiddlewareException(this ILogger logger, string context, Exception exception)
-        {
-            _migrationsEndPointMiddlewareException(logger, context, exception);
-        }
+        [LoggerMessage(7, LogLevel.Error, "An error occurred while applying the migrations for '{ContextTypeName}'. See InnerException for details:", EventName = "MigrationsEndPointException")]
+        public static partial void MigrationsEndPointMiddlewareException(this ILogger logger, string contextTypeName, Exception exception);
+    }
 
-        public static void AttemptingToMatchException(this ILogger logger, Type exceptionType)
-        {
-            _attemptingToMatchException(logger, exceptionType, null);
-        }
+    internal static partial class DatabaseErrorPageMiddlewareLoggerExtensions
+    {
+        [LoggerMessage(1, LogLevel.Debug, "{ExceptionType} occurred, checking if Entity Framework recorded this exception as resulting from a failed database operation.", EventName = "AttemptingToMatchException")]
+        public static partial void AttemptingToMatchException(this ILogger logger, Type exceptionType);
 
-        public static void NoRecordedException(this ILogger logger)
-        {
-            _noRecordedException(logger, null);
-        }
+        [LoggerMessage(2, LogLevel.Debug, "Entity Framework did not record any exceptions due to failed database operations. This means the current exception is not a failed Entity Framework database operation, or the current exception occurred from a DbContext that was not obtained from request services.", EventName = "NoRecordedException")]
+        public static partial void NoRecordedException(this ILogger logger);
 
-        public static void NoMatch(this ILogger logger)
-        {
-            _noMatch(logger, null);
-        }
+        [LoggerMessage(3, LogLevel.Debug, "The current exception (and its inner exceptions) do not match the last exception Entity Framework recorded due to a failed database operation. This means the database operation exception was handled and another exception occurred later in the request.", EventName = "NoMatchFound")]
+        public static partial void NoMatch(this ILogger logger);
 
-        public static void Matched(this ILogger logger)
-        {
-            _matched(logger, null);
-        }
+        [LoggerMessage(4, LogLevel.Debug, "Entity Framework recorded that the current exception was due to a failed database operation. Attempting to show database error page.", EventName = "MatchFound")]
+        public static partial void Matched(this ILogger logger);
 
-        public static void NotRelationalDatabase(this ILogger logger)
-        {
-            _notRelationalDatabase(logger, null);
-        }
+        [LoggerMessage(6, LogLevel.Debug, "The target data store is not a relational database. Skipping the database error page.", EventName = "NotRelationalDatabase")]
+        public static partial void NotRelationalDatabase(this ILogger logger);
 
-        public static void ContextNotRegisteredDatabaseErrorPageMiddleware(this ILogger logger, string contextTypeName)
-        {
-            _contextNotRegisteredDatabaseErrorPageMiddleware(logger, contextTypeName, null);
-        }
+        [LoggerMessage(5, LogLevel.Error, "The context type '{ContextTypeName}' was not found in services. This usually means the context was not registered in services during startup. You probably want to call AddScoped<>() inside the UseServices(...) call in your application startup code. Skipping display of the database error page.", EventName = "ContextNotRegistered")]
+        public static partial void ContextNotRegisteredDatabaseErrorPageMiddleware(this ILogger logger, string contextTypeName);
 
-        public static void DatabaseErrorPageMiddlewareException(this ILogger logger, Exception exception)
-        {
-            _databaseErrorPageMiddlewareException(logger, exception);
-        }
+        [LoggerMessage(7, LogLevel.Error, "An exception occurred while calculating the database error page content. Skipping display of the database error page.", EventName = "DatabaseErrorPageException")]
+        public static partial void DatabaseErrorPageMiddlewareException(this ILogger logger, Exception exception);
+    }
 
-        public static void ResponseStartedDatabaseDeveloperPageExceptionFilter(this ILogger logger)
-        {
-            _responseStartedDatabaseDeveloperPageExceptionFilter(logger, null);
-        }
+    internal static partial class DatabaseDeveloperPageExceptionFilterLoggerExtensions
+    {
+        [LoggerMessage(1, LogLevel.Warning, "The response has already started, the next developer page exception filter will not be executed.", EventName = "ResponseStarted")]
+        public static partial void ResponseStartedDatabaseDeveloperPageExceptionFilter(this ILogger logger);
     }
 }

+ 14 - 39
src/Middleware/Diagnostics/src/DiagnosticsLoggerExtensions.cs

@@ -1,55 +1,30 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
-using Microsoft.AspNetCore.Builder;
 using Microsoft.Extensions.Logging;
 
 namespace Microsoft.AspNetCore.Diagnostics
 {
-    internal static class DiagnosticsLoggerExtensions
+    internal static partial class DiagnosticsLoggerExtensions
     {
         // ExceptionHandlerMiddleware & DeveloperExceptionPageMiddleware
-        private static readonly Action<ILogger, Exception> _unhandledException =
-            LoggerMessage.Define(LogLevel.Error, new EventId(1, "UnhandledException"), "An unhandled exception has occurred while executing the request.");
+        [LoggerMessage(1, LogLevel.Error, "An unhandled exception has occurred while executing the request.", EventName = "UnhandledException")]
+        public static partial void UnhandledException(this ILogger logger, Exception exception);
 
         // ExceptionHandlerMiddleware
-        private static readonly Action<ILogger, Exception?> _responseStartedErrorHandler =
-            LoggerMessage.Define(LogLevel.Warning, new EventId(2, "ResponseStarted"), "The response has already started, the error handler will not be executed.");
+        [LoggerMessage(2, LogLevel.Warning, "The response has already started, the error handler will not be executed.", EventName = "ResponseStarted")]
+        public static partial void ResponseStartedErrorHandler(this ILogger logger);
 
-        private static readonly Action<ILogger, Exception> _errorHandlerException =
-            LoggerMessage.Define(LogLevel.Error, new EventId(3, "Exception"), "An exception was thrown attempting to execute the error handler.");
-
-        // DeveloperExceptionPageMiddleware
-        private static readonly Action<ILogger, Exception?> _responseStartedErrorPageMiddleware =
-            LoggerMessage.Define(LogLevel.Warning, new EventId(2, "ResponseStarted"), "The response has already started, the error page middleware will not be executed.");
-
-        private static readonly Action<ILogger, Exception> _displayErrorPageException =
-            LoggerMessage.Define(LogLevel.Error, new EventId(3, "DisplayErrorPageException"), "An exception was thrown attempting to display the error page.");
-
-        public static void UnhandledException(this ILogger logger, Exception exception)
-        {
-            _unhandledException(logger, exception);
-        }
-
-        public static void ResponseStartedErrorHandler(this ILogger logger)
-        {
-            _responseStartedErrorHandler(logger, null);
-        }
-
-        public static void ErrorHandlerException(this ILogger logger, Exception exception)
-        {
-            _errorHandlerException(logger, exception);
-        }
+        [LoggerMessage(3, LogLevel.Error, "An exception was thrown attempting to execute the error handler.", EventName = "Exception")]
+        public static partial void ErrorHandlerException(this ILogger logger, Exception exception);
+    }
 
-        public static void ResponseStartedErrorPageMiddleware(this ILogger logger)
-        {
-            _responseStartedErrorPageMiddleware(logger, null);
-        }
+    internal static partial class DeveloperExceptionPageMiddlewareLoggerExtensions
+    {
+        [LoggerMessage(2, LogLevel.Warning, "The response has already started, the error page middleware will not be executed.", EventName = "ResponseStarted")]
+        public static partial void ResponseStartedErrorPageMiddleware(this ILogger logger);
 
-        public static void DisplayErrorPageException(this ILogger logger, Exception exception)
-        {
-            _displayErrorPageException(logger, exception);
-        }
+        [LoggerMessage(3, LogLevel.Error, "An exception was thrown attempting to display the error page.", EventName = "DisplayErrorPageException")]
+        public static partial void DisplayErrorPageException(this ILogger logger, Exception exception);
     }
 }

+ 8 - 22
src/Middleware/HttpLogging/src/FileLoggerProcessor.cs

@@ -18,7 +18,7 @@ using Microsoft.Extensions.Options;
 
 namespace Microsoft.AspNetCore.HttpLogging
 {
-    internal class FileLoggerProcessor : IAsyncDisposable
+    internal partial class FileLoggerProcessor : IAsyncDisposable
     {
         private const int _maxQueuedMessages = 1024;
 
@@ -319,31 +319,17 @@ namespace Microsoft.AspNetCore.HttpLogging
             return Task.CompletedTask;
         }
 
-        private static class Log
+        private static partial class Log
         {
-            private static readonly Action<ILogger, Exception> _writeMessagesFailed =
-                LoggerMessage.Define(
-                    LogLevel.Debug,
-                    new EventId(1, "WriteMessagesFailed"),
-                    "Failed to write all messages.");
 
-            public static void WriteMessagesFailed(ILogger logger, Exception ex) => _writeMessagesFailed(logger, ex);
+            [LoggerMessage(1, LogLevel.Debug, "Failed to write all messages.", EventName = "WriteMessagesFailed")]
+            public static partial void WriteMessagesFailed(ILogger logger, Exception ex);
 
-            private static readonly Action<ILogger, string, Exception> _createDirectoryFailed =
-                LoggerMessage.Define<string>(
-                    LogLevel.Debug,
-                    new EventId(2, "CreateDirectoryFailed"),
-                    "Failed to create directory {Path}.");
+            [LoggerMessage(2, LogLevel.Debug, "Failed to create directory {Path}.", EventName = "CreateDirectoryFailed")]
+            public static partial void CreateDirectoryFailed(ILogger logger, string path, Exception ex);
 
-            public static void CreateDirectoryFailed(ILogger logger, string path, Exception ex) => _createDirectoryFailed(logger, path, ex);
-
-            private static readonly Action<ILogger, Exception?> _maxFilesReached =
-                LoggerMessage.Define(
-                    LogLevel.Warning,
-                    new EventId(3, "MaxFilesReached"),
-                    $"Limit of {W3CLoggerOptions.MaxFileCount} files per day has been reached");
-
-            public static void MaxFilesReached(ILogger logger) => _maxFilesReached(logger, null);
+            [LoggerMessage(3, LogLevel.Warning, "Limit of 10000 files per day has been reached", EventName = "MaxFilesReached")]
+            public static partial void MaxFilesReached(ILogger logger);
         }
     }
 

+ 13 - 18
src/Middleware/HttpLogging/src/HttpLoggingExtensions.cs

@@ -1,25 +1,12 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
 using Microsoft.Extensions.Logging;
 
 namespace Microsoft.AspNetCore.HttpLogging
 {
-    internal static class HttpLoggingExtensions
+    internal static partial class HttpLoggingExtensions
     {
-        private static readonly Action<ILogger, string, Exception?> _requestBody =
-            LoggerMessage.Define<string>(LogLevel.Information, new EventId(3, "RequestBody"), "RequestBody: {Body}");
-
-        private static readonly Action<ILogger, string, Exception?> _responseBody =
-            LoggerMessage.Define<string>(LogLevel.Information, new EventId(4, "ResponseBody"), "ResponseBody: {Body}");
-
-        private static readonly Action<ILogger, Exception?> _decodeFailure =
-            LoggerMessage.Define(LogLevel.Debug, new EventId(5, "DecodeFaulure"), "Decode failure while converting body.");
-
-        private static readonly Action<ILogger, Exception?> _unrecognizedMediaType =
-            LoggerMessage.Define(LogLevel.Debug, new EventId(6, "UnrecognizedMediaType"), "Unrecognized Content-Type for body.");
-
         public static void RequestLog(this ILogger logger, HttpRequestLog requestLog) => logger.Log(
             LogLevel.Information,
             new EventId(1, "RequestLogLog"),
@@ -32,9 +19,17 @@ namespace Microsoft.AspNetCore.HttpLogging
             responseLog,
             exception: null,
             formatter: HttpResponseLog.Callback);
-        public static void RequestBody(this ILogger logger, string body) => _requestBody(logger, body, null);
-        public static void ResponseBody(this ILogger logger, string body) => _responseBody(logger, body, null);
-        public static void DecodeFailure(this ILogger logger, Exception ex) => _decodeFailure(logger, ex);
-        public static void UnrecognizedMediaType(this ILogger logger) => _unrecognizedMediaType(logger, null);
+
+        [LoggerMessage(3, LogLevel.Information, "RequestBody: {Body}", EventName = "RequestBody")]
+        public static partial void RequestBody(this ILogger logger, string body);
+
+        [LoggerMessage(4, LogLevel.Information, "ResponseBody: {Body}", EventName = "ResponseBody")]
+        public static partial void ResponseBody(this ILogger logger, string body);
+
+        [LoggerMessage(5, LogLevel.Debug, "Decode failure while converting body.", EventName = "DecodeFaulure")]
+        public static partial void DecodeFailure(this ILogger logger, Exception ex);
+
+        [LoggerMessage(6, LogLevel.Debug, "Unrecognized Content-Type for body.", EventName = "UnrecognizedMediaType")]
+        public static partial void UnrecognizedMediaType(this ILogger logger);
     }
 }

+ 2 - 1
src/Middleware/HttpLogging/src/W3CLoggerOptions.cs

@@ -17,7 +17,8 @@ namespace Microsoft.AspNetCore.HttpLogging
         private string _fileName = "w3clog-";
         private string _logDirectory = "";
         private TimeSpan _flushInterval = TimeSpan.FromSeconds(1);
-        internal static int MaxFileCount = 10000;
+        // Update the MaxFilesReached log message in FileLoggerProcessor if this value changes.
+        internal const int MaxFileCount = 10000;
 
         /// <summary>
         /// Gets or sets a strictly positive value representing the maximum log size in bytes or null for no limit.

+ 3 - 15
src/Middleware/HttpOverrides/src/LoggingExtensions.cs

@@ -5,21 +5,9 @@ using System;
 
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, Exception?> _noCertificate;
-
-        static LoggingExtensions()
-        {
-            _noCertificate = LoggerMessage.Define(
-                eventId: new EventId(0, "NoCertificate"),
-                logLevel: LogLevel.Warning,
-                formatString: "Could not read certificate from header.");
-        }
-
-        public static void NoCertificate(this ILogger logger, Exception exception)
-        {
-            _noCertificate(logger, exception);
-        }
+        [LoggerMessage(0, LogLevel.Warning, "Could not read certificate from header.", EventName = "NoCertificate")]
+        public static partial void NoCertificate(this ILogger logger, Exception exception);
     }
 }

+ 29 - 146
src/Middleware/Rewrite/src/Extensions/RewriteMiddlewareLoggingExtensions.cs

@@ -6,164 +6,47 @@ using Microsoft.Extensions.Logging;
 
 namespace Microsoft.AspNetCore.Rewrite.Logging
 {
-    internal static class RewriteMiddlewareLoggingExtensions
+    internal static partial class RewriteMiddlewareLoggingExtensions
     {
-        private static readonly Action<ILogger, string, Exception?> _requestContinueResults;
-        private static readonly Action<ILogger, string, int, Exception?> _requestResponseComplete;
-        private static readonly Action<ILogger, string, Exception?> _requestStopRules;
-        private static readonly Action<ILogger, string?, Exception?> _urlRewriteNotMatchedRule;
-        private static readonly Action<ILogger, string?, Exception?> _urlRewriteMatchedRule;
-        private static readonly Action<ILogger, Exception?> _modRewriteNotMatchedRule;
-        private static readonly Action<ILogger, Exception?> _modRewriteMatchedRule;
-        private static readonly Action<ILogger, Exception?> _redirectedToHttps;
-        private static readonly Action<ILogger, Exception?> _redirectedToWww;
-        private static readonly Action<ILogger, Exception?> _redirectedToNonWww;
-        private static readonly Action<ILogger, string, Exception?> _redirectedRequest;
-        private static readonly Action<ILogger, string, Exception?> _rewrittenRequest;
-        private static readonly Action<ILogger, string, Exception?> _abortedRequest;
-        private static readonly Action<ILogger, string, Exception?> _customResponse;
+        [LoggerMessage(1, LogLevel.Debug, "Request is continuing in applying rules. Current url is {currentUrl}", EventName = "RequestContinueResults")]
+        public static partial void RewriteMiddlewareRequestContinueResults(this ILogger logger, string currentUrl);
 
-        static RewriteMiddlewareLoggingExtensions()
-        {
-            _requestContinueResults = LoggerMessage.Define<string>(
-                            LogLevel.Debug,
-                            new EventId(1, "RequestContinueResults"),
-                            "Request is continuing in applying rules. Current url is {currentUrl}");
+        [LoggerMessage(2, LogLevel.Debug, "Request is done processing. Location header '{Location}' with status code '{StatusCode}'.", EventName = "RequestResponseComplete")]
+        public static partial void RewriteMiddlewareRequestResponseComplete(this ILogger logger, string location, int statusCode);
 
-            _requestResponseComplete = LoggerMessage.Define<string, int>(
-                            LogLevel.Debug,
-                            new EventId(2, "RequestResponseComplete"),
-                            "Request is done processing. Location header '{Location}' with status code '{StatusCode}'.");
+        [LoggerMessage(3, LogLevel.Debug, "Request is done applying rules. Url was rewritten to {rewrittenUrl}", EventName = "RequestStopRules")]
+        public static partial void RewriteMiddlewareRequestStopRules(this ILogger logger, string rewrittenUrl);
 
-            _requestStopRules = LoggerMessage.Define<string>(
-                            LogLevel.Debug,
-                            new EventId(3, "RequestStopRules"),
-                            "Request is done applying rules. Url was rewritten to {rewrittenUrl}");
+        [LoggerMessage(4, LogLevel.Debug, "Request did not match current rule '{Name}'.", EventName = "UrlRewriteNotMatchedRule")]
+        public static partial void UrlRewriteNotMatchedRule(this ILogger logger, string? name);
 
-            _urlRewriteNotMatchedRule = LoggerMessage.Define<string?>(
-                            LogLevel.Debug,
-                            new EventId(4, "UrlRewriteNotMatchedRule"),
-                            "Request did not match current rule '{Name}'.");
+        [LoggerMessage(5, LogLevel.Debug, "Request matched current UrlRewriteRule '{Name}'.", EventName = "UrlRewriteMatchedRule")]
+        public static partial void UrlRewriteMatchedRule(this ILogger logger, string? name);
 
-            _urlRewriteMatchedRule = LoggerMessage.Define<string?>(
-                            LogLevel.Debug,
-                            new EventId(5, "UrlRewriteMatchedRule"),
-                            "Request matched current UrlRewriteRule '{Name}'.");
+        [LoggerMessage(6, LogLevel.Debug, "Request matched current ModRewriteRule.", EventName = "ModRewriteNotMatchedRule")]
+        public static partial void ModRewriteNotMatchedRule(this ILogger logger);
 
-            _modRewriteNotMatchedRule = LoggerMessage.Define(
-                            LogLevel.Debug,
-                            new EventId(6, "ModRewriteNotMatchedRule"),
-                            "Request matched current ModRewriteRule.");
+        [LoggerMessage(7, LogLevel.Debug, "Request matched current ModRewriteRule.", EventName = "ModRewriteMatchedRule")]
+        public static partial void ModRewriteMatchedRule(this ILogger logger);
 
-            _modRewriteMatchedRule = LoggerMessage.Define(
-                            LogLevel.Debug,
-                            new EventId(7, "ModRewriteMatchedRule"),
-                            "Request matched current ModRewriteRule.");
+        [LoggerMessage(8, LogLevel.Information, "Request redirected to HTTPS", EventName = "RedirectedToHttps")]
+        public static partial void RedirectedToHttps(this ILogger logger);
 
-            _redirectedToHttps = LoggerMessage.Define(
-                            LogLevel.Information,
-                            new EventId(8, "RedirectedToHttps"),
-                            "Request redirected to HTTPS");
+        [LoggerMessage(13, LogLevel.Information, "Request redirected to www", EventName = "RedirectedToWww")]
+        public static partial void RedirectedToWww(this ILogger logger);
 
-            _redirectedRequest = LoggerMessage.Define<string>(
-                            LogLevel.Information,
-                            new EventId(9, "RedirectedRequest"),
-                            "Request was redirected to {redirectedUrl}");
+        [LoggerMessage(14, LogLevel.Information, "Request redirected to root domain from www subdomain", EventName = "RedirectedToNonWww")]
+        public static partial void RedirectedToNonWww(this ILogger logger);
+        [LoggerMessage(9, LogLevel.Information, "Request was redirected to {redirectedUrl}", EventName = "RedirectedRequest")]
+        public static partial void RedirectedRequest(this ILogger logger, string redirectedUrl);
 
-            _rewrittenRequest = LoggerMessage.Define<string>(
-                            LogLevel.Information,
-                            new EventId(10, "RewritetenRequest"),
-                            "Request was rewritten to {rewrittenUrl}");
+        [LoggerMessage(10, LogLevel.Information, "Request was rewritten to {rewrittenUrl}", EventName = "RewritetenRequest")]
+        public static partial void RewrittenRequest(this ILogger logger, string rewrittenUrl);
 
-            _abortedRequest = LoggerMessage.Define<string>(
-                            LogLevel.Debug,
-                            new EventId(11, "AbortedRequest"),
-                            "Request to {requestedUrl} was aborted");
+        [LoggerMessage(11, LogLevel.Debug, "Request to {requestedUrl} was aborted", EventName = "AbortedRequest")]
+        public static partial void AbortedRequest(this ILogger logger, string requestedUrl);
 
-            _customResponse = LoggerMessage.Define<string>(
-                            LogLevel.Debug,
-                            new EventId(12, "CustomResponse"),
-                            "Request to {requestedUrl} was ended");
-
-            _redirectedToWww = LoggerMessage.Define(
-                            LogLevel.Information,
-                            new EventId(13, "RedirectedToWww"),
-                            "Request redirected to www");
-
-            _redirectedToNonWww = LoggerMessage.Define(
-                            LogLevel.Information,
-                            new EventId(14, "RedirectedToNonWww"),
-                            "Request redirected to root domain from www subdomain");
-        }
-
-        public static void RewriteMiddlewareRequestContinueResults(this ILogger logger, string currentUrl)
-        {
-            _requestContinueResults(logger, currentUrl, null);
-        }
-
-        public static void RewriteMiddlewareRequestResponseComplete(this ILogger logger, string location, int statusCode)
-        {
-            _requestResponseComplete(logger, location, statusCode, null);
-        }
-
-        public static void RewriteMiddlewareRequestStopRules(this ILogger logger, string rewrittenUrl)
-        {
-            _requestStopRules(logger, rewrittenUrl, null);
-        }
-
-        public static void UrlRewriteNotMatchedRule(this ILogger logger, string? name)
-        {
-            _urlRewriteNotMatchedRule(logger, name, null);
-        }
-
-        public static void UrlRewriteMatchedRule(this ILogger logger, string? name)
-        {
-            _urlRewriteMatchedRule(logger, name, null);
-        }
-
-        public static void ModRewriteNotMatchedRule(this ILogger logger)
-        {
-            _modRewriteNotMatchedRule(logger, null);
-        }
-
-        public static void ModRewriteMatchedRule(this ILogger logger)
-        {
-            _modRewriteMatchedRule(logger, null);
-        }
-
-        public static void RedirectedToHttps(this ILogger logger)
-        {
-            _redirectedToHttps(logger, null);
-        }
-
-        public static void RedirectedToWww(this ILogger logger)
-        {
-            _redirectedToWww(logger, null);
-        }
-
-        public static void RedirectedToNonWww(this ILogger logger)
-        {
-            _redirectedToNonWww(logger, null);
-        }
-
-        public static void RedirectedRequest(this ILogger logger, string redirectedUrl)
-        {
-            _redirectedRequest(logger, redirectedUrl, null);
-        }
-
-        public static void RewrittenRequest(this ILogger logger, string rewrittenUrl)
-        {
-            _rewrittenRequest(logger, rewrittenUrl, null);
-        }
-
-        public static void AbortedRequest(this ILogger logger, string requestedUrl)
-        {
-            _abortedRequest(logger, requestedUrl, null);
-        }
-
-        public static void CustomResponse(this ILogger logger, string requestedUrl)
-        {
-            _customResponse(logger, requestedUrl, null);
-        }
+        [LoggerMessage(12, LogLevel.Debug, "Request to {requestedUrl} was ended", EventName = "CustomResponse")]
+        public static partial void CustomResponse(this ILogger logger, string requestedUrl);
     }
 }

+ 27 - 125
src/Middleware/Session/src/LoggingExtensions.cs

@@ -5,143 +5,45 @@ using System;
 
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, Exception?> _errorClosingTheSession;
-        private static readonly Action<ILogger, string, Exception?> _accessingExpiredSession;
-        private static readonly Action<ILogger, string, string, Exception?> _sessionStarted;
-        private static readonly Action<ILogger, string, string, int, Exception?> _sessionLoaded;
-        private static readonly Action<ILogger, string, string, int, Exception?> _sessionStored;
-        private static readonly Action<ILogger, string, Exception?> _sessionCacheReadException;
-        private static readonly Action<ILogger, Exception?> _errorUnprotectingCookie;
-        private static readonly Action<ILogger, Exception?> _sessionLoadingTimeout;
-        private static readonly Action<ILogger, Exception?> _sessionCommitTimeout;
-        private static readonly Action<ILogger, Exception?> _sessionCommitCanceled;
-        private static readonly Action<ILogger, Exception?> _sessionRefreshTimeout;
-        private static readonly Action<ILogger, Exception?> _sessionRefreshCanceled;
-        private static readonly Action<ILogger, Exception?> _sessionNotAvailable;
+        [LoggerMessage(1, LogLevel.Error, "Error closing the session.", EventName = "ErrorClosingTheSession")]
+        public static partial void ErrorClosingTheSession(this ILogger logger, Exception exception);
 
-        private static readonly LogDefineOptions SkipEnabledCheckLogOptions = new() { SkipEnabledCheck = true };
+        [LoggerMessage(2, LogLevel.Information, "Accessing expired session, Key:{sessionKey}", EventName = "AccessingExpiredSession")]
+        public static partial void AccessingExpiredSession(this ILogger logger, string sessionKey);
 
-        static LoggingExtensions()
-        {
-            _errorClosingTheSession = LoggerMessage.Define(
-                eventId: new EventId(1, "ErrorClosingTheSession"),
-                logLevel: LogLevel.Error,
-                formatString: "Error closing the session.");
-            _accessingExpiredSession = LoggerMessage.Define<string>(
-                eventId: new EventId(2, "AccessingExpiredSession"),
-                logLevel: LogLevel.Information,
-                formatString: "Accessing expired session, Key:{sessionKey}");
-            _sessionStarted = LoggerMessage.Define<string, string>(
-                logLevel: LogLevel.Information,
-                eventId: new EventId(3, "SessionStarted"),
-                formatString: "Session started; Key:{sessionKey}, Id:{sessionId}",
-                SkipEnabledCheckLogOptions);
-            _sessionLoaded = LoggerMessage.Define<string, string, int>(
-                logLevel: LogLevel.Debug,
-                eventId: new EventId(4, "SessionLoaded"),
-                formatString: "Session loaded; Key:{sessionKey}, Id:{sessionId}, Count:{count}",
-                SkipEnabledCheckLogOptions);
-            _sessionStored = LoggerMessage.Define<string, string, int>(
-                eventId: new EventId(5, "SessionStored"),
-                logLevel: LogLevel.Debug,
-                formatString: "Session stored; Key:{sessionKey}, Id:{sessionId}, Count:{count}");
-            _sessionCacheReadException = LoggerMessage.Define<string>(
-                logLevel: LogLevel.Error,
-                eventId: new EventId(6, "SessionCacheReadException"),
-                formatString: "Session cache read exception, Key:{sessionKey}",
-                SkipEnabledCheckLogOptions);
-            _errorUnprotectingCookie = LoggerMessage.Define(
-                eventId: new EventId(7, "ErrorUnprotectingCookie"),
-                logLevel: LogLevel.Warning,
-                formatString: "Error unprotecting the session cookie.");
-            _sessionLoadingTimeout = LoggerMessage.Define(
-                eventId: new EventId(8, "SessionLoadingTimeout"),
-                logLevel: LogLevel.Warning,
-                formatString: "Loading the session timed out.");
-            _sessionCommitTimeout = LoggerMessage.Define(
-                eventId: new EventId(9, "SessionCommitTimeout"),
-                logLevel: LogLevel.Warning,
-                formatString: "Committing the session timed out.");
-            _sessionCommitCanceled = LoggerMessage.Define(
-                eventId: new EventId(10, "SessionCommitCanceled"),
-                logLevel: LogLevel.Information,
-                formatString: "Committing the session was canceled.");
-            _sessionRefreshTimeout = LoggerMessage.Define(
-                eventId: new EventId(11, "SessionRefreshTimeout"),
-                logLevel: LogLevel.Warning,
-                formatString: "Refreshing the session timed out.");
-            _sessionRefreshCanceled = LoggerMessage.Define(
-                eventId: new EventId(12, "SessionRefreshCanceled"),
-                logLevel: LogLevel.Information,
-                formatString: "Refreshing the session was canceled.");
-            _sessionNotAvailable = LoggerMessage.Define(
-                eventId: new EventId(13, "SessionCommitNotAvailable"),
-                logLevel: LogLevel.Information,
-                formatString: "Session cannot be committed since it is unavailable.");
-        }
+        [LoggerMessage(3, LogLevel.Information, "Session started; Key:{sessionKey}, Id:{sessionId}", EventName = "SessionStarted", SkipEnabledCheck = true)]
+        public static partial void SessionStarted(this ILogger logger, string sessionKey, string sessionId);
 
-        public static void ErrorClosingTheSession(this ILogger logger, Exception exception)
-        {
-            _errorClosingTheSession(logger, exception);
-        }
+        [LoggerMessage(4, LogLevel.Debug, "Session loaded; Key:{sessionKey}, Id:{sessionId}, Count:{count}", EventName = "SessionLoaded", SkipEnabledCheck = true)]
+        public static partial void SessionLoaded(this ILogger logger, string sessionKey, string sessionId, int count);
 
-        public static void AccessingExpiredSession(this ILogger logger, string sessionKey)
-        {
-            _accessingExpiredSession(logger, sessionKey, null);
-        }
+        [LoggerMessage(5, LogLevel.Debug, "Session stored; Key:{sessionKey}, Id:{sessionId}, Count:{count}", EventName = "SessionStored")]
+        public static partial void SessionStored(this ILogger logger, string sessionKey, string sessionId, int count);
 
-        public static void SessionStarted(this ILogger logger, string sessionKey, string sessionId)
-        {
-            _sessionStarted(logger, sessionKey, sessionId, null);
-        }
+        [LoggerMessage(6, LogLevel.Error, "Session cache read exception, Key:{sessionKey}", EventName = "SessionCacheReadException", SkipEnabledCheck = true)]
+        public static partial void SessionCacheReadException(this ILogger logger, string sessionKey, Exception exception);
 
-        public static void SessionLoaded(this ILogger logger, string sessionKey, string sessionId, int count)
-        {
-            _sessionLoaded(logger, sessionKey, sessionId, count, null);
-        }
+        [LoggerMessage(7, LogLevel.Warning, "Error unprotecting the session cookie.", EventName = "ErrorUnprotectingCookie")]
+        public static partial void ErrorUnprotectingSessionCookie(this ILogger logger, Exception exception);
 
-        public static void SessionStored(this ILogger logger, string sessionKey, string sessionId, int count)
-        {
-            _sessionStored(logger, sessionKey, sessionId, count, null);
-        }
+        [LoggerMessage(8, LogLevel.Warning, "Loading the session timed out.", EventName = "SessionLoadingTimeout")]
+        public static partial void SessionLoadingTimeout(this ILogger logger);
 
-        public static void SessionCacheReadException(this ILogger logger, string sessionKey, Exception exception)
-        {
-            _sessionCacheReadException(logger, sessionKey, exception);
-        }
+        [LoggerMessage(9, LogLevel.Warning, "Committing the session timed out.", EventName = "SessionCommitTimeout")]
+        public static partial void SessionCommitTimeout(this ILogger logger);
 
-        public static void ErrorUnprotectingSessionCookie(this ILogger logger, Exception exception)
-        {
-            _errorUnprotectingCookie(logger, exception);
-        }
+        [LoggerMessage(10, LogLevel.Information, "Committing the session was canceled.", EventName = "SessionCommitCanceled")]
+        public static partial void SessionCommitCanceled(this ILogger logger);
 
-        public static void SessionLoadingTimeout(this ILogger logger)
-        {
-            _sessionLoadingTimeout(logger, null);
-        }
+        [LoggerMessage(11, LogLevel.Warning, "Refreshing the session timed out.", EventName = "SessionRefreshTimeout")]
+        public static partial void SessionRefreshTimeout(this ILogger logger);
 
-        public static void SessionCommitTimeout(this ILogger logger)
-        {
-            _sessionCommitTimeout(logger, null);
-        }
+        [LoggerMessage(12, LogLevel.Information, "Refreshing the session was canceled.", EventName = "SessionRefreshCanceled")]
+        public static partial void SessionRefreshCanceled(this ILogger logger);
 
-        public static void SessionCommitCanceled(this ILogger logger)
-        {
-            _sessionCommitCanceled(logger, null);
-        }
-
-        public static void SessionRefreshTimeout(this ILogger logger)
-        {
-            _sessionRefreshTimeout(logger, null);
-        }
-
-        public static void SessionRefreshCanceled(this ILogger logger)
-        {
-            _sessionRefreshCanceled(logger, null);
-        }
-
-        public static void SessionNotAvailable(this ILogger logger) => _sessionNotAvailable(logger, null);
+        [LoggerMessage(13, LogLevel.Information, "Session cannot be committed since it is unavailable.", EventName = "SessionCommitNotAvailable")]
+        public static partial void SessionNotAvailable(this ILogger logger);
     }
 }

+ 28 - 120
src/Middleware/StaticFiles/src/LoggerExtensions.cs

@@ -1,7 +1,6 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
 using Microsoft.Extensions.Logging;
 using Microsoft.Extensions.Primitives;
 
@@ -10,82 +9,13 @@ namespace Microsoft.AspNetCore.StaticFiles
     /// <summary>
     /// Defines *all* the logger messages produced by static files
     /// </summary>
-    internal static class LoggerExtensions
+    internal static partial class LoggerExtensions
     {
-        private static readonly Action<ILogger, string, Exception?> _methodNotSupported;
-        private static readonly Action<ILogger, string, string, Exception?> _fileServed;
-        private static readonly Action<ILogger, string, Exception?> _pathMismatch;
-        private static readonly Action<ILogger, string, Exception?> _fileTypeNotSupported;
-        private static readonly Action<ILogger, string, Exception?> _fileNotFound;
-        private static readonly Action<ILogger, string, Exception?> _fileNotModified;
-        private static readonly Action<ILogger, string, Exception?> _preconditionFailed;
-        private static readonly Action<ILogger, int, string, Exception?> _handled;
-        private static readonly Action<ILogger, string, Exception?> _rangeNotSatisfiable;
-        private static readonly Action<ILogger, StringValues, string, Exception?> _sendingFileRange;
-        private static readonly Action<ILogger, StringValues, string, Exception?> _copyingFileRange;
-        private static readonly Action<ILogger, Exception?> _writeCancelled;
-        private static readonly Action<ILogger, Exception?> _endpointMatched;
+        [LoggerMessage(1, LogLevel.Debug, "{Method} requests are not supported", EventName = "MethodNotSupported")]
+        public static partial void RequestMethodNotSupported(this ILogger logger, string method);
 
-        static LoggerExtensions()
-        {
-            _methodNotSupported = LoggerMessage.Define<string>(
-                logLevel: LogLevel.Debug,
-                eventId: new EventId(1, "MethodNotSupported"),
-                formatString: "{Method} requests are not supported");
-            _fileServed = LoggerMessage.Define<string, string>(
-               logLevel: LogLevel.Information,
-               eventId: new EventId(2, "FileServed"),
-               formatString: "Sending file. Request path: '{VirtualPath}'. Physical path: '{PhysicalPath}'");
-            _pathMismatch = LoggerMessage.Define<string>(
-                logLevel: LogLevel.Debug,
-                eventId: new EventId(3, "PathMismatch"),
-                formatString: "The request path {Path} does not match the path filter");
-            _fileTypeNotSupported = LoggerMessage.Define<string>(
-                logLevel: LogLevel.Debug,
-                eventId: new EventId(4, "FileTypeNotSupported"),
-                formatString: "The request path {Path} does not match a supported file type");
-            _fileNotFound = LoggerMessage.Define<string>(
-                logLevel: LogLevel.Debug,
-                eventId: new EventId(5, "FileNotFound"),
-                formatString: "The request path {Path} does not match an existing file");
-            _fileNotModified = LoggerMessage.Define<string>(
-                logLevel: LogLevel.Information,
-                eventId: new EventId(6, "FileNotModified"),
-                formatString: "The file {Path} was not modified");
-            _preconditionFailed = LoggerMessage.Define<string>(
-                logLevel: LogLevel.Information,
-                eventId: new EventId(7, "PreconditionFailed"),
-                formatString: "Precondition for {Path} failed");
-            _handled = LoggerMessage.Define<int, string>(
-                logLevel: LogLevel.Debug,
-                eventId: new EventId(8, "Handled"),
-                formatString: "Handled. Status code: {StatusCode} File: {Path}");
-            _rangeNotSatisfiable = LoggerMessage.Define<string>(
-                logLevel: LogLevel.Warning,
-                eventId: new EventId(9, "RangeNotSatisfiable"),
-                formatString: "Range not satisfiable for {Path}");
-            _sendingFileRange = LoggerMessage.Define<StringValues, string>(
-                logLevel: LogLevel.Information,
-                eventId: new EventId(10, "SendingFileRange"),
-                formatString: "Sending {Range} of file {Path}");
-            _copyingFileRange = LoggerMessage.Define<StringValues, string>(
-                logLevel: LogLevel.Debug,
-                eventId: new EventId(11, "CopyingFileRange"),
-                formatString: "Copying {Range} of file {Path} to the response body");
-            _writeCancelled = LoggerMessage.Define(
-                logLevel: LogLevel.Debug,
-                eventId: new EventId(14, "WriteCancelled"),
-                formatString: "The file transmission was cancelled");
-            _endpointMatched = LoggerMessage.Define(
-                logLevel: LogLevel.Debug,
-                eventId: new EventId(15, "EndpointMatched"),
-                formatString: "Static files was skipped as the request already matched an endpoint.");
-        }
-
-        public static void RequestMethodNotSupported(this ILogger logger, string method)
-        {
-            _methodNotSupported(logger, method, null);
-        }
+        [LoggerMessage(2, LogLevel.Information, "Sending file. Request path: '{VirtualPath}'. Physical path: '{PhysicalPath}'", EventName = "FileServed")]
+        private static partial void FileServedCore(this ILogger logger, string virtualPath, string physicalPath);
 
         public static void FileServed(this ILogger logger, string virtualPath, string physicalPath)
         {
@@ -93,62 +23,40 @@ namespace Microsoft.AspNetCore.StaticFiles
             {
                 physicalPath = "N/A";
             }
-            _fileServed(logger, virtualPath, physicalPath, null);
+            FileServedCore(logger, virtualPath, physicalPath);
         }
 
-        public static void EndpointMatched(this ILogger logger)
-        {
-            _endpointMatched(logger, null);
-        }
+        [LoggerMessage(15, LogLevel.Debug, "Static files was skipped as the request already matched an endpoint.", EventName = "EndpointMatched")]
+        public static partial void EndpointMatched(this ILogger logger);
 
-        public static void PathMismatch(this ILogger logger, string path)
-        {
-            _pathMismatch(logger, path, null);
-        }
+        [LoggerMessage(3, LogLevel.Debug, "The request path {Path} does not match the path filter", EventName = "PathMismatch")]
+        public static partial void PathMismatch(this ILogger logger, string path);
 
-        public static void FileTypeNotSupported(this ILogger logger, string path)
-        {
-            _fileTypeNotSupported(logger, path, null);
-        }
+        [LoggerMessage(4, LogLevel.Debug, "The request path {Path} does not match a supported file type", EventName = "FileTypeNotSupported")]
+        public static partial void FileTypeNotSupported(this ILogger logger, string path);
 
-        public static void FileNotFound(this ILogger logger, string path)
-        {
-            _fileNotFound(logger, path, null);
-        }
+        [LoggerMessage(5, LogLevel.Debug, "The request path {Path} does not match an existing file", EventName = "FileNotFound")]
+        public static partial void FileNotFound(this ILogger logger, string path);
 
-        public static void FileNotModified(this ILogger logger, string path)
-        {
-            _fileNotModified(logger, path, null);
-        }
+        [LoggerMessage(6, LogLevel.Information, "The file {Path} was not modified", EventName = "FileNotModified")]
+        public static partial void FileNotModified(this ILogger logger, string path);
 
-        public static void PreconditionFailed(this ILogger logger, string path)
-        {
-            _preconditionFailed(logger, path, null);
-        }
+        [LoggerMessage(7, LogLevel.Information, "Precondition for {Path} failed", EventName = "PreconditionFailed")]
+        public static partial void PreconditionFailed(this ILogger logger, string path);
 
-        public static void Handled(this ILogger logger, int statusCode, string path)
-        {
-            _handled(logger, statusCode, path, null);
-        }
+        [LoggerMessage(8, LogLevel.Debug, "Handled. Status code: {StatusCode} File: {Path}", EventName = "Handled")]
+        public static partial void Handled(this ILogger logger, int statusCode, string path);
 
-        public static void RangeNotSatisfiable(this ILogger logger, string path)
-        {
-            _rangeNotSatisfiable(logger, path, null);
-        }
+        [LoggerMessage(9, LogLevel.Warning, "Range not satisfiable for {Path}", EventName = "RangeNotSatisfiable")]
+        public static partial void RangeNotSatisfiable(this ILogger logger, string path);
 
-        public static void SendingFileRange(this ILogger logger, StringValues range, string path)
-        {
-            _sendingFileRange(logger, range, path, null);
-        }
+        [LoggerMessage(10, LogLevel.Information, "Sending {Range} of file {Path}", EventName = "SendingFileRange")]
+        public static partial void SendingFileRange(this ILogger logger, StringValues range, string path);
 
-        public static void CopyingFileRange(this ILogger logger, StringValues range, string path)
-        {
-            _copyingFileRange(logger, range, path, null);
-        }
+        [LoggerMessage(11, LogLevel.Debug, "Copying {Range} of file {Path} to the response body", EventName = "CopyingFileRange")]
+        public static partial void CopyingFileRange(this ILogger logger, StringValues range, string path);
 
-        public static void WriteCancelled(this ILogger logger, Exception ex)
-        {
-            _writeCancelled(logger, ex);
-        }
+        [LoggerMessage(14, LogLevel.Debug, "The file transmission was cancelled", EventName = "WriteCancelled")]
+        public static partial void WriteCancelled(this ILogger logger, Exception ex);
     }
 }

+ 6 - 16
src/Middleware/WebSockets/src/WebSocketMiddleware.cs

@@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.WebSockets
     /// Enables accepting WebSocket requests by adding a <see cref="IHttpWebSocketFeature"/>
     /// to the <see cref="HttpContext"/> if the request is a valid WebSocket request.
     /// </summary>
-    public class WebSocketMiddleware
+    public partial class WebSocketMiddleware
     {
         private readonly RequestDelegate _next;
         private readonly WebSocketOptions _options;
@@ -275,23 +275,13 @@ namespace Microsoft.AspNetCore.WebSockets
             }
         }
 
-        private static class Log
+        private static partial class Log
         {
-            private static readonly Action<ILogger, string, Exception?> _compressionAccepted =
-                LoggerMessage.Define<string>(LogLevel.Debug, new EventId(1, "CompressionAccepted"), "WebSocket compression negotiation accepted with values '{CompressionResponse}'.");
+            [LoggerMessage(1, LogLevel.Debug, "WebSocket compression negotiation accepted with values '{CompressionResponse}'.", EventName = "CompressionAccepted")]
+            public static partial void CompressionAccepted(ILogger logger, string compressionResponse);
 
-            private static readonly Action<ILogger, Exception?> _compressionNotAccepted =
-                LoggerMessage.Define(LogLevel.Debug, new EventId(2, "CompressionNotAccepted"), "Compression negotiation not accepted by server.");
-
-            public static void CompressionAccepted(ILogger logger, string response)
-            {
-                _compressionAccepted(logger, response, null);
-            }
-
-            public static void CompressionNotAccepted(ILogger logger)
-            {
-                _compressionNotAccepted(logger, null);
-            }
+            [LoggerMessage(2, LogLevel.Debug, "Compression negotiation not accepted by server.", EventName = "CompressionNotAccepted")]
+            public static partial void CompressionNotAccepted(ILogger logger);
         }
     }
 }

+ 9 - 48
src/Security/Authentication/Certificate/src/LoggingExtensions.cs

@@ -1,59 +1,20 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
-using System.Collections.Generic;
-
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, Exception?> _noCertificate;
-        private static readonly Action<ILogger, Exception?> _notHttps;
-        private static readonly Action<ILogger, string, string, Exception?> _certRejected;
-        private static readonly Action<ILogger, string, string, Exception?> _certFailedValidation;
-
-        static LoggingExtensions()
-        {
-            _noCertificate = LoggerMessage.Define(
-                eventId: new EventId(0, "NoCertificate"),
-                logLevel: LogLevel.Debug,
-                formatString: "No client certificate found.");
-
-            _certRejected = LoggerMessage.Define<string, string>(
-                eventId: new EventId(1, "CertificateRejected"),
-                logLevel: LogLevel.Warning,
-                formatString: "{CertificateType} certificate rejected, subject was {Subject}.");
-
-            _certFailedValidation = LoggerMessage.Define<string, string>(
-                eventId: new EventId(2, "CertificateFailedValidation"),
-                logLevel: LogLevel.Warning,
-                formatString: "Certificate validation failed, subject was {Subject}." + Environment.NewLine + "{ChainErrors}");
-
-            _notHttps = LoggerMessage.Define(
-                eventId: new EventId(3, "NotHttps"),
-                logLevel: LogLevel.Debug,
-                formatString: "Not https, skipping certificate authentication.");
-        }
-
-        public static void NoCertificate(this ILogger logger)
-        {
-            _noCertificate(logger, null);
-        }
+        [LoggerMessage(0, LogLevel.Debug, "No client certificate found.", EventName = "NoCertificate")]
+        public static partial void NoCertificate(this ILogger logger);
 
-        public static void NotHttps(this ILogger logger)
-        {
-            _notHttps(logger, null);
-        }
+        [LoggerMessage(3, LogLevel.Debug, "Not https, skipping certificate authentication.", EventName = "NotHttps")]
+        public static partial void NotHttps(this ILogger logger);
 
-        public static void CertificateRejected(this ILogger logger, string certificateType, string subject)
-        {
-            _certRejected(logger, certificateType, subject, null);
-        }
+        [LoggerMessage(1, LogLevel.Warning, "{CertificateType} certificate rejected, subject was {Subject}.", EventName = "CertificateRejected")]
+        public static partial void CertificateRejected(this ILogger logger, string certificateType, string subject);
 
-        public static void CertificateFailedValidation(this ILogger logger, string subject, IEnumerable<string> chainedErrors)
-        {
-            _certFailedValidation(logger, subject, String.Join(Environment.NewLine, chainedErrors), null);
-        }
+        [LoggerMessage(2, LogLevel.Warning, "Certificate validation failed, subject was {Subject}. {ChainErrors}", EventName = "CertificateFailedValidation")]
+        public static partial void CertificateFailedValidation(this ILogger logger, string subject, IEnumerable<string> chainErrors);
     }
 }

+ 5 - 18
src/Security/Authentication/Cookies/src/LoggingExtensions.cs

@@ -5,25 +5,12 @@ using System;
 
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, string, Exception?> _authenticationSchemeSignedIn = LoggerMessage.Define<string>(
-                eventId: new EventId(10, "AuthenticationSchemeSignedIn"),
-                logLevel: LogLevel.Information,
-                formatString: "AuthenticationScheme: {AuthenticationScheme} signed in.");
-        private static readonly Action<ILogger, string, Exception?> _authenticationSchemeSignedOut = LoggerMessage.Define<string>(
-                eventId: new EventId(11, "AuthenticationSchemeSignedOut"),
-                logLevel: LogLevel.Information,
-                formatString: "AuthenticationScheme: {AuthenticationScheme} signed out.");
+        [LoggerMessage(10, LogLevel.Information, "AuthenticationScheme: {AuthenticationScheme} signed in.", EventName = "AuthenticationSchemeSignedIn")]
+        public static partial void AuthenticationSchemeSignedIn(this ILogger logger, string authenticationScheme);
 
-        public static void AuthenticationSchemeSignedIn(this ILogger logger, string authenticationScheme)
-        {
-            _authenticationSchemeSignedIn(logger, authenticationScheme, null);
-        }
-
-        public static void AuthenticationSchemeSignedOut(this ILogger logger, string authenticationScheme)
-        {
-            _authenticationSchemeSignedOut(logger, authenticationScheme, null);
-        }
+        [LoggerMessage(11, LogLevel.Information, "AuthenticationScheme: {AuthenticationScheme} signed out.", EventName = "AuthenticationSchemeSignedOut")]
+        public static partial void AuthenticationSchemeSignedOut(this ILogger logger, string authenticationScheme);
     }
 }

+ 29 - 134
src/Security/Authentication/Core/src/LoggingExtensions.cs

@@ -1,155 +1,50 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
-
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, string, Exception?> _authenticationSchemeAuthenticated;
-        private static readonly Action<ILogger, string, Exception?> _authenticationSchemeNotAuthenticated;
-        private static readonly Action<ILogger, string, string, Exception?> _authenticationSchemeNotAuthenticatedWithFailure;
-        private static readonly Action<ILogger, string, Exception?> _authenticationSchemeChallenged;
-        private static readonly Action<ILogger, string, Exception?> _authenticationSchemeForbidden;
-        private static readonly Action<ILogger, string, Exception?> _remoteAuthenticationError;
-        private static readonly Action<ILogger, Exception?> _signInHandled;
-        private static readonly Action<ILogger, Exception?> _signInSkipped;
-        private static readonly Action<ILogger, string, Exception?> _correlationPropertyNotFound;
-        private static readonly Action<ILogger, string, Exception?> _correlationCookieNotFound;
-        private static readonly Action<ILogger, string, string, Exception?> _unexpectedCorrelationCookieValue;
-        private static readonly Action<ILogger, Exception?> _accessDeniedError;
-        private static readonly Action<ILogger, Exception?> _accessDeniedContextHandled;
-        private static readonly Action<ILogger, Exception?> _accessDeniedContextSkipped;
-
-        static LoggingExtensions()
-        {
-            _remoteAuthenticationError = LoggerMessage.Define<string>(
-                eventId: new EventId(4, "RemoteAuthenticationFailed"),
-                logLevel: LogLevel.Information,
-                formatString: "Error from RemoteAuthentication: {ErrorMessage}.");
-            _signInHandled = LoggerMessage.Define(
-                eventId: new EventId(5, "SignInHandled"),
-                logLevel: LogLevel.Debug,
-                formatString: "The SigningIn event returned Handled.");
-            _signInSkipped = LoggerMessage.Define(
-                eventId: new EventId(6, "SignInSkipped"),
-                logLevel: LogLevel.Debug,
-                formatString: "The SigningIn event returned Skipped.");
-            _authenticationSchemeNotAuthenticatedWithFailure = LoggerMessage.Define<string, string>(
-                eventId: new EventId(7, "AuthenticationSchemeNotAuthenticatedWithFailure"),
-                logLevel: LogLevel.Information,
-                formatString: "{AuthenticationScheme} was not authenticated. Failure message: {FailureMessage}");
-            _authenticationSchemeAuthenticated = LoggerMessage.Define<string>(
-                eventId: new EventId(8, "AuthenticationSchemeAuthenticated"),
-                logLevel: LogLevel.Debug,
-                formatString: "AuthenticationScheme: {AuthenticationScheme} was successfully authenticated.");
-            _authenticationSchemeNotAuthenticated = LoggerMessage.Define<string>(
-                eventId: new EventId(9, "AuthenticationSchemeNotAuthenticated"),
-                logLevel: LogLevel.Debug,
-                formatString: "AuthenticationScheme: {AuthenticationScheme} was not authenticated.");
-            _authenticationSchemeChallenged = LoggerMessage.Define<string>(
-                eventId: new EventId(12, "AuthenticationSchemeChallenged"),
-                logLevel: LogLevel.Information,
-                formatString: "AuthenticationScheme: {AuthenticationScheme} was challenged.");
-            _authenticationSchemeForbidden = LoggerMessage.Define<string>(
-                eventId: new EventId(13, "AuthenticationSchemeForbidden"),
-                logLevel: LogLevel.Information,
-                formatString: "AuthenticationScheme: {AuthenticationScheme} was forbidden.");
-            _correlationPropertyNotFound = LoggerMessage.Define<string>(
-                eventId: new EventId(14, "CorrelationPropertyNotFound"),
-                logLevel: LogLevel.Warning,
-                formatString: "{CorrelationProperty} state property not found.");
-            _correlationCookieNotFound = LoggerMessage.Define<string>(
-                eventId: new EventId(15, "CorrelationCookieNotFound"),
-                logLevel: LogLevel.Warning,
-                formatString: "'{CorrelationCookieName}' cookie not found.");
-            _unexpectedCorrelationCookieValue = LoggerMessage.Define<string, string>(
-                eventId: new EventId(16, "UnexpectedCorrelationCookieValue"),
-               logLevel: LogLevel.Warning,
-               formatString: "The correlation cookie value '{CorrelationCookieName}' did not match the expected value '{CorrelationCookieValue}'.");
-            _accessDeniedError = LoggerMessage.Define(
-                eventId: new EventId(17, "AccessDenied"),
-                logLevel: LogLevel.Information,
-                formatString: "Access was denied by the resource owner or by the remote server.");
-            _accessDeniedContextHandled = LoggerMessage.Define(
-                eventId: new EventId(18, "AccessDeniedContextHandled"),
-                logLevel: LogLevel.Debug,
-                formatString: "The AccessDenied event returned Handled.");
-            _accessDeniedContextSkipped = LoggerMessage.Define(
-                eventId: new EventId(19, "AccessDeniedContextSkipped"),
-                logLevel: LogLevel.Debug,
-                formatString: "The AccessDenied event returned Skipped.");
-        }
-
-        public static void AuthenticationSchemeAuthenticated(this ILogger logger, string authenticationScheme)
-        {
-            _authenticationSchemeAuthenticated(logger, authenticationScheme, null);
-        }
+        [LoggerMessage(4, LogLevel.Information, "Error from RemoteAuthentication: {ErrorMessage}.", EventName = "RemoteAuthenticationFailed")]
+        public static partial void RemoteAuthenticationError(this ILogger logger, string errorMessage);
 
-        public static void AuthenticationSchemeNotAuthenticated(this ILogger logger, string authenticationScheme)
-        {
-            _authenticationSchemeNotAuthenticated(logger, authenticationScheme, null);
-        }
+        [LoggerMessage(5, LogLevel.Debug, "The SigningIn event returned Handled.", EventName = "SignInHandled")]
+        public static partial void SignInHandled(this ILogger logger);
 
-        public static void AuthenticationSchemeNotAuthenticatedWithFailure(this ILogger logger, string authenticationScheme, string failureMessage)
-        {
-            _authenticationSchemeNotAuthenticatedWithFailure(logger, authenticationScheme, failureMessage, null);
-        }
+        [LoggerMessage(6, LogLevel.Debug, "The SigningIn event returned Skipped.", EventName = "SignInSkipped")]
+        public static partial void SignInSkipped(this ILogger logger);
 
-        public static void AuthenticationSchemeChallenged(this ILogger logger, string authenticationScheme)
-        {
-            _authenticationSchemeChallenged(logger, authenticationScheme, null);
-        }
+        [LoggerMessage(7, LogLevel.Information, "{AuthenticationScheme} was not authenticated. Failure message: {FailureMessage}", EventName = "AuthenticationSchemeNotAuthenticatedWithFailure")]
+        public static partial void AuthenticationSchemeNotAuthenticatedWithFailure(this ILogger logger, string authenticationScheme, string failureMessage);
 
-        public static void AuthenticationSchemeForbidden(this ILogger logger, string authenticationScheme)
-        {
-            _authenticationSchemeForbidden(logger, authenticationScheme, null);
-        }
+        [LoggerMessage(8, LogLevel.Debug, "AuthenticationScheme: {AuthenticationScheme} was successfully authenticated.", EventName = "AuthenticationSchemeAuthenticated")]
+        public static partial void AuthenticationSchemeAuthenticated(this ILogger logger, string authenticationScheme);
 
-        public static void RemoteAuthenticationError(this ILogger logger, string errorMessage)
-        {
-            _remoteAuthenticationError(logger, errorMessage, null);
-        }
+        [LoggerMessage(9, LogLevel.Debug, "AuthenticationScheme: {AuthenticationScheme} was not authenticated.", EventName = "AuthenticationSchemeNotAuthenticated")]
+        public static partial void AuthenticationSchemeNotAuthenticated(this ILogger logger, string authenticationScheme);
 
-        public static void SignInHandled(this ILogger logger)
-        {
-            _signInHandled(logger, null);
-        }
+        [LoggerMessage(12, LogLevel.Information, "AuthenticationScheme: {AuthenticationScheme} was challenged.", EventName = "AuthenticationSchemeChallenged")]
+        public static partial void AuthenticationSchemeChallenged(this ILogger logger, string authenticationScheme);
 
-        public static void SignInSkipped(this ILogger logger)
-        {
-            _signInSkipped(logger, null);
-        }
+        [LoggerMessage(13, LogLevel.Information, "AuthenticationScheme: {AuthenticationScheme} was forbidden.", EventName = "AuthenticationSchemeForbidden")]
+        public static partial void AuthenticationSchemeForbidden(this ILogger logger, string authenticationScheme);
 
-        public static void CorrelationPropertyNotFound(this ILogger logger, string correlationPrefix)
-        {
-            _correlationPropertyNotFound(logger, correlationPrefix, null);
-        }
+        [LoggerMessage(14, LogLevel.Warning, "{CorrelationProperty} state property not found.", EventName = "CorrelationPropertyNotFound")]
+        public static partial void CorrelationPropertyNotFound(this ILogger logger, string correlationProperty);
 
-        public static void CorrelationCookieNotFound(this ILogger logger, string cookieName)
-        {
-            _correlationCookieNotFound(logger, cookieName, null);
-        }
+        [LoggerMessage(15, LogLevel.Warning, "'{CorrelationCookieName}' cookie not found.", EventName = "CorrelationCookieNotFound")]
+        public static partial void CorrelationCookieNotFound(this ILogger logger, string correlationCookieName);
 
-        public static void UnexpectedCorrelationCookieValue(this ILogger logger, string cookieName, string cookieValue)
-        {
-            _unexpectedCorrelationCookieValue(logger, cookieName, cookieValue, null);
-        }
+        [LoggerMessage(16, LogLevel.Warning, "The correlation cookie value '{CorrelationCookieName}' did not match the expected value '{CorrelationCookieValue}'.", EventName = "UnexpectedCorrelationCookieValue")]
+        public static partial void UnexpectedCorrelationCookieValue(this ILogger logger, string correlationCookieName, string correlationCookieValue);
 
-        public static void AccessDeniedError(this ILogger logger)
-        {
-            _accessDeniedError(logger, null);
-        }
+        [LoggerMessage(17, LogLevel.Information, "Access was denied by the resource owner or by the remote server.", EventName = "AccessDenied")]
+        public static partial void AccessDeniedError(this ILogger logger);
 
-        public static void AccessDeniedContextHandled(this ILogger logger)
-        {
-            _accessDeniedContextHandled(logger, null);
-        }
+        [LoggerMessage(18, LogLevel.Debug, "The AccessDenied event returned Handled.", EventName = "AccessDeniedContextHandled")]
+        public static partial void AccessDeniedContextHandled(this ILogger logger);
 
-        public static void AccessDeniedContextSkipped(this ILogger logger)
-        {
-            _accessDeniedContextSkipped(logger, null);
-        }
+        [LoggerMessage(19, LogLevel.Debug, "The AccessDenied event returned Skipped.", EventName = "AccessDeniedContextSkipped")]
+        public static partial void AccessDeniedContextSkipped(this ILogger logger);
     }
 }

+ 25 - 92
src/Security/Authentication/Negotiate/src/Internal/NegotiateLoggingExtensions.cs

@@ -1,111 +1,44 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
-
 namespace Microsoft.Extensions.Logging
 {
-    internal static class NegotiateLoggingExtensions
+    internal static partial class NegotiateLoggingExtensions
     {
-        private static readonly Action<ILogger, Exception?> _incompleteNegotiateChallenge;
-        private static readonly Action<ILogger, Exception?> _negotiateComplete;
-        private static readonly Action<ILogger, Exception?> _enablingCredentialPersistence;
-        private static readonly Action<ILogger, string, Exception?> _disablingCredentialPersistence;
-        private static readonly Action<ILogger, Exception> _exceptionProcessingAuth;
-        private static readonly Action<ILogger, Exception> _credentialError;
-        private static readonly Action<ILogger, Exception> _clientError;
-        private static readonly Action<ILogger, Exception?> _challengeNegotiate;
-        private static readonly Action<ILogger, Exception?> _reauthenticating;
-        private static readonly Action<ILogger, Exception?> _deferring;
-        private static readonly Action<ILogger, string, Exception?> _negotiateError;
-        private static readonly Action<ILogger, string, Exception?> _protocolNotSupported;
-
-        static NegotiateLoggingExtensions()
-        {
-            _incompleteNegotiateChallenge = LoggerMessage.Define(
-                eventId: new EventId(1, "IncompleteNegotiateChallenge"),
-                logLevel: LogLevel.Information,
-                formatString: "Incomplete Negotiate handshake, sending an additional 401 Negotiate challenge.");
-            _negotiateComplete = LoggerMessage.Define(
-                eventId: new EventId(2, "NegotiateComplete"),
-                logLevel: LogLevel.Debug,
-                formatString: "Completed Negotiate authentication.");
-            _enablingCredentialPersistence = LoggerMessage.Define(
-                eventId: new EventId(3, "EnablingCredentialPersistence"),
-                logLevel: LogLevel.Debug,
-                formatString: "Enabling credential persistence for a complete Kerberos handshake.");
-            _disablingCredentialPersistence = LoggerMessage.Define<string>(
-                eventId: new EventId(4, "DisablingCredentialPersistence"),
-                logLevel: LogLevel.Debug,
-                formatString: "Disabling credential persistence for a complete {protocol} handshake.");
-            _exceptionProcessingAuth = LoggerMessage.Define(
-                eventId: new EventId(5, "ExceptionProcessingAuth"),
-                logLevel: LogLevel.Error,
-                formatString: "An exception occurred while processing the authentication request.");
-            _challengeNegotiate = LoggerMessage.Define(
-                eventId: new EventId(6, "ChallengeNegotiate"),
-                logLevel: LogLevel.Debug,
-                formatString: "Challenged 401 Negotiate.");
-            _reauthenticating = LoggerMessage.Define(
-                eventId: new EventId(7, "Reauthenticating"),
-                logLevel: LogLevel.Debug,
-                formatString: "Negotiate data received for an already authenticated connection, Re-authenticating.");
-            _deferring = LoggerMessage.Define(
-                eventId: new EventId(8, "Deferring"),
-                logLevel: LogLevel.Information,
-                formatString: "Deferring to the server's implementation of Windows Authentication.");
-            _credentialError = LoggerMessage.Define(
-                eventId: new EventId(9, "CredentialError"),
-                logLevel: LogLevel.Debug,
-                formatString: "There was a problem with the users credentials.");
-            _clientError = LoggerMessage.Define(
-                eventId: new EventId(10, "ClientError"),
-                logLevel: LogLevel.Debug,
-                formatString: "The users authentication request was invalid.");
-            _negotiateError = LoggerMessage.Define<string>(
-                eventId: new EventId(11, "NegotiateError"),
-                logLevel: LogLevel.Debug,
-                formatString: "Negotiate error code: {error}.");
-            _protocolNotSupported = LoggerMessage.Define<string>(
-                eventId: new EventId(12, "ProtocolNotSupported"),
-                logLevel: LogLevel.Debug,
-                formatString: "Negotiate is not supported with {protocol}.");
-        }
-
-        public static void IncompleteNegotiateChallenge(this ILogger logger)
-            => _incompleteNegotiateChallenge(logger, null);
+        [LoggerMessage(1, LogLevel.Information, "Incomplete Negotiate handshake, sending an additional 401 Negotiate challenge.", EventName = "IncompleteNegotiateChallenge")]
+        public static partial void IncompleteNegotiateChallenge(this ILogger logger);
 
-        public static void NegotiateComplete(this ILogger logger)
-            => _negotiateComplete(logger, null);
+        [LoggerMessage(2, LogLevel.Debug, "Completed Negotiate authentication.", EventName = "NegotiateComplete")]
+        public static partial void NegotiateComplete(this ILogger logger);
 
-        public static void EnablingCredentialPersistence(this ILogger logger)
-            => _enablingCredentialPersistence(logger, null);
+        [LoggerMessage(3, LogLevel.Debug, "Enabling credential persistence for a complete Kerberos handshake.", EventName = "EnablingCredentialPersistence")]
+        public static partial void EnablingCredentialPersistence(this ILogger logger);
 
-        public static void DisablingCredentialPersistence(this ILogger logger, string protocol)
-            => _disablingCredentialPersistence(logger, protocol, null);
+        [LoggerMessage(4, LogLevel.Debug, "Disabling credential persistence for a complete {protocol} handshake.", EventName = "DisablingCredentialPersistence")]
+        public static partial void DisablingCredentialPersistence(this ILogger logger, string protocol);
 
-        public static void ExceptionProcessingAuth(this ILogger logger, Exception ex)
-            => _exceptionProcessingAuth(logger, ex);
+        [LoggerMessage(5, LogLevel.Error, "An exception occurred while processing the authentication request.", EventName = "ExceptionProcessingAuth")]
+        public static partial void ExceptionProcessingAuth(this ILogger logger, Exception ex);
 
-        public static void ChallengeNegotiate(this ILogger logger)
-            => _challengeNegotiate(logger, null);
+        [LoggerMessage(6, LogLevel.Debug, "Challenged 401 Negotiate.", EventName = "ChallengeNegotiate")]
+        public static partial void ChallengeNegotiate(this ILogger logger);
 
-        public static void Reauthenticating(this ILogger logger)
-            => _reauthenticating(logger, null);
+        [LoggerMessage(7, LogLevel.Debug, "Negotiate data received for an already authenticated connection, Re-authenticating.", EventName = "Reauthenticating")]
+        public static partial void Reauthenticating(this ILogger logger);
 
-        public static void Deferring(this ILogger logger)
-            => _deferring(logger, null);
+        [LoggerMessage(8, LogLevel.Information, "Deferring to the server's implementation of Windows Authentication.", EventName = "Deferring")]
+        public static partial void Deferring(this ILogger logger);
 
-        public static void CredentialError(this ILogger logger, Exception ex)
-            => _credentialError(logger, ex);
+        [LoggerMessage(9, LogLevel.Debug, "There was a problem with the users credentials.", EventName = "CredentialError")]
+        public static partial void CredentialError(this ILogger logger, Exception ex);
 
-        public static void ClientError(this ILogger logger, Exception ex)
-            => _clientError(logger, ex);
+        [LoggerMessage(10, LogLevel.Debug, "The users authentication request was invalid.", EventName = "ClientError")]
+        public static partial void ClientError(this ILogger logger, Exception ex);
 
-        public static void NegotiateError(this ILogger logger, string error)
-            => _negotiateError(logger, error, null);
+        [LoggerMessage(11, LogLevel.Debug, "Negotiate error code: {error}.", EventName = "NegotiateError")]
+        public static partial void NegotiateError(this ILogger logger, string error);
 
-        public static void ProtocolNotSupported(this ILogger logger, string protocol)
-            => _protocolNotSupported(logger, protocol, null);
+        [LoggerMessage(12, LogLevel.Debug, "Negotiate is not supported with {protocol}.", EventName = "ProtocolNotSupported")]
+        public static partial void ProtocolNotSupported(this ILogger logger, string protocol);
     }
 }

+ 3 - 15
src/Security/Authentication/OAuth/src/LoggingExtensions.cs

@@ -1,23 +1,11 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
-
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, string, string, Exception?> _handleChallenge;
-
-        static LoggingExtensions()
-        {
-            _handleChallenge = LoggerMessage.Define<string, string>(
-                eventId: new EventId(1, "HandleChallenge"),
-                logLevel: LogLevel.Debug,
-                formatString: "HandleChallenge with Location: {Location}; and Set-Cookie: {Cookie}.");
-        }
-
-        public static void HandleChallenge(this ILogger logger, string location, string cookie)
-            => _handleChallenge(logger, location, cookie, null);
+        [LoggerMessage(1, LogLevel.Debug, "HandleChallenge with Location: {Location}; and Set-Cookie: {Cookie}.", EventName = "HandleChallenge")]
+        public static partial void HandleChallenge(this ILogger logger, string location, string cookie);
     }
 }

+ 160 - 532
src/Security/Authentication/OpenIdConnect/src/LoggingExtensions.cs

@@ -1,540 +1,168 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
-
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, Exception?> _redirectToIdentityProviderForSignOutHandledResponse;
-        private static readonly Action<ILogger, Exception?> _redirectToIdentityProviderHandledResponse;
-        private static readonly Action<ILogger, Exception?> _signOutCallbackRedirectHandledResponse;
-        private static readonly Action<ILogger, Exception?> _signOutCallbackRedirectSkipped;
-        private static readonly Action<ILogger, Exception?> _updatingConfiguration;
-        private static readonly Action<ILogger, Exception?> _receivedIdToken;
-        private static readonly Action<ILogger, Exception?> _redeemingCodeForTokens;
-        private static readonly Action<ILogger, string, Exception?> _enteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync;
-        private static readonly Action<ILogger, string, Exception?> _enteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync;
-        private static readonly Action<ILogger, string, Exception?> _enteringOpenIdAuthenticationHandlerHandleSignOutAsync;
-        private static readonly Action<ILogger, string, Exception?> _messageReceived;
-        private static readonly Action<ILogger, Exception?> _messageReceivedContextHandledResponse;
-        private static readonly Action<ILogger, Exception?> _messageReceivedContextSkipped;
-        private static readonly Action<ILogger, Exception?> _authorizationCodeReceived;
-        private static readonly Action<ILogger, Exception?> _configurationManagerRequestRefreshCalled;
-        private static readonly Action<ILogger, Exception?> _tokenResponseReceived;
-        private static readonly Action<ILogger, Exception?> _tokenValidatedHandledResponse;
-        private static readonly Action<ILogger, Exception?> _tokenValidatedSkipped;
-        private static readonly Action<ILogger, Exception?> _authenticationFailedContextHandledResponse;
-        private static readonly Action<ILogger, Exception?> _authenticationFailedContextSkipped;
-        private static readonly Action<ILogger, Exception?> _authorizationCodeReceivedContextHandledResponse;
-        private static readonly Action<ILogger, Exception?> _authorizationCodeReceivedContextSkipped;
-        private static readonly Action<ILogger, Exception?> _tokenResponseReceivedHandledResponse;
-        private static readonly Action<ILogger, Exception?> _tokenResponseReceivedSkipped;
-        private static readonly Action<ILogger, string, Exception?> _userInformationReceived;
-        private static readonly Action<ILogger, Exception?> _userInformationReceivedHandledResponse;
-        private static readonly Action<ILogger, Exception?> _userInformationReceivedSkipped;
-        private static readonly Action<ILogger, string, Exception?> _invalidLogoutQueryStringRedirectUrl;
-        private static readonly Action<ILogger, Exception?> _nullOrEmptyAuthorizationResponseState;
-        private static readonly Action<ILogger, Exception?> _unableToReadAuthorizationResponseState;
-        private static readonly Action<ILogger, string, string, string, Exception?> _responseError;
-        private static readonly Action<ILogger, string, string, string, int, Exception?> _responseErrorWithStatusCode;
-        private static readonly Action<ILogger, Exception> _exceptionProcessingMessage;
-        private static readonly Action<ILogger, Exception?> _accessTokenNotAvailable;
-        private static readonly Action<ILogger, Exception?> _retrievingClaims;
-        private static readonly Action<ILogger, Exception?> _userInfoEndpointNotSet;
-        private static readonly Action<ILogger, Exception> _unableToProtectNonceCookie;
-        private static readonly Action<ILogger, string, Exception?> _invalidAuthenticationRequestUrl;
-        private static readonly Action<ILogger, string, Exception?> _unableToReadIdToken;
-        private static readonly Action<ILogger, string?, Exception?> _invalidSecurityTokenType;
-        private static readonly Action<ILogger, string, Exception?> _unableToValidateIdToken;
-        private static readonly Action<ILogger, string, Exception?> _postAuthenticationLocalRedirect;
-        private static readonly Action<ILogger, string, Exception?> _postSignOutRedirect;
-        private static readonly Action<ILogger, Exception?> _remoteSignOutHandledResponse;
-        private static readonly Action<ILogger, Exception?> _remoteSignOutSkipped;
-        private static readonly Action<ILogger, Exception?> _remoteSignOut;
-        private static readonly Action<ILogger, Exception?> _remoteSignOutSessionIdMissing;
-        private static readonly Action<ILogger, Exception?> _remoteSignOutSessionIdInvalid;
-        private static readonly Action<ILogger, string, Exception?> _authenticationSchemeSignedOut;
-        private static readonly Action<ILogger, string, string, Exception?> _handleChallenge;
-        private static readonly Action<ILogger, Exception?> _remoteSignOutIssuerMissing;
-        private static readonly Action<ILogger, Exception?> _remoteSignOutIssuerInvalid;
-
-        static LoggingExtensions()
-        {
-            // Final
-            _redirectToIdentityProviderForSignOutHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(1, "RedirectToIdentityProviderForSignOutHandledResponse"),
-                logLevel: LogLevel.Debug,
-                formatString: "RedirectToIdentityProviderForSignOut.HandledResponse");
-            _invalidLogoutQueryStringRedirectUrl = LoggerMessage.Define<string>(
-                eventId: new EventId(3, "InvalidLogoutQueryStringRedirectUrl"),
-                logLevel: LogLevel.Warning,
-                formatString: "The query string for Logout is not a well-formed URI. Redirect URI: '{RedirectUrl}'.");
-            _enteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync = LoggerMessage.Define<string>(
-                eventId: new EventId(4, "EnteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync"),
-                logLevel: LogLevel.Trace,
-                formatString: "Entering {OpenIdConnectHandlerType}'s HandleUnauthorizedAsync.");
-            _enteringOpenIdAuthenticationHandlerHandleSignOutAsync = LoggerMessage.Define<string>(
-                eventId: new EventId(14, "EnteringOpenIdAuthenticationHandlerHandleSignOutAsync"),
-                logLevel: LogLevel.Trace,
-                formatString: "Entering {OpenIdConnectHandlerType}'s HandleSignOutAsync.");
-            _postAuthenticationLocalRedirect = LoggerMessage.Define<string>(
-                eventId: new EventId(5, "PostAuthenticationLocalRedirect"),
-                logLevel: LogLevel.Trace,
-                formatString: "Using properties.RedirectUri for 'local redirect' post authentication: '{RedirectUri}'.");
-            _redirectToIdentityProviderHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(6, "RedirectToIdentityProviderHandledResponse"),
-                logLevel: LogLevel.Debug,
-                formatString: "RedirectToIdentityProvider.HandledResponse");
-            _invalidAuthenticationRequestUrl = LoggerMessage.Define<string>(
-                eventId: new EventId(8, "InvalidAuthenticationRequestUrl"),
-                logLevel: LogLevel.Warning,
-                formatString: "The redirect URI is not well-formed. The URI is: '{AuthenticationRequestUrl}'.");
-            _enteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync = LoggerMessage.Define<string>(
-                eventId: new EventId(9, "EnteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync"),
-                logLevel: LogLevel.Trace,
-                formatString: "Entering {OpenIdConnectHandlerType}'s HandleRemoteAuthenticateAsync.");
-            _nullOrEmptyAuthorizationResponseState = LoggerMessage.Define(
-                eventId: new EventId(10, "NullOrEmptyAuthorizationResponseState"),
-                logLevel: LogLevel.Debug,
-                formatString: "message.State is null or empty.");
-            _unableToReadAuthorizationResponseState = LoggerMessage.Define(
-                eventId: new EventId(11, "UnableToReadAuthorizationResponseState"),
-                logLevel: LogLevel.Debug,
-                formatString: "Unable to read the message.State.");
-            _responseError = LoggerMessage.Define<string, string, string>(
-                eventId: new EventId(12, "ResponseError"),
-                logLevel: LogLevel.Error,
-                formatString: "Message contains error: '{Error}', error_description: '{ErrorDescription}', error_uri: '{ErrorUri}'.");
-            _responseErrorWithStatusCode = LoggerMessage.Define<string, string, string, int>(
-                eventId: new EventId(52, "ResponseErrorWithStatusCode"),
-                logLevel: LogLevel.Error,
-                formatString: "Message contains error: '{Error}', error_description: '{ErrorDescription}', error_uri: '{ErrorUri}', status code '{StatusCode}'.");
-            _updatingConfiguration = LoggerMessage.Define(
-                eventId: new EventId(13, "UpdatingConfiguration"),
-                logLevel: LogLevel.Debug,
-                formatString: "Updating configuration");
-            _tokenValidatedHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(15, "TokenValidatedHandledResponse"),
-                logLevel: LogLevel.Debug,
-                formatString: "TokenValidated.HandledResponse");
-            _tokenValidatedSkipped = LoggerMessage.Define(
-                eventId: new EventId(16, "TokenValidatedSkipped"),
-                logLevel: LogLevel.Debug,
-                formatString: "TokenValidated.Skipped");
-            _exceptionProcessingMessage = LoggerMessage.Define(
-                eventId: new EventId(17, "ExceptionProcessingMessage"),
-                logLevel: LogLevel.Error,
-                formatString: "Exception occurred while processing message.");
-            _configurationManagerRequestRefreshCalled = LoggerMessage.Define(
-                eventId: new EventId(18, "ConfigurationManagerRequestRefreshCalled"),
-                logLevel: LogLevel.Debug,
-                formatString: "Exception of type 'SecurityTokenSignatureKeyNotFoundException' thrown, Options.ConfigurationManager.RequestRefresh() called.");
-            _redeemingCodeForTokens = LoggerMessage.Define(
-                eventId: new EventId(19, "RedeemingCodeForTokens"),
-                logLevel: LogLevel.Debug,
-                formatString: "Redeeming code for tokens.");
-            _retrievingClaims = LoggerMessage.Define(
-                eventId: new EventId(20, "RetrievingClaims"),
-                logLevel: LogLevel.Trace,
-                formatString: "Retrieving claims from the user info endpoint.");
-            _receivedIdToken = LoggerMessage.Define(
-                eventId: new EventId(21, "ReceivedIdToken"),
-                logLevel: LogLevel.Debug,
-                formatString: "Received 'id_token'");
-            _userInfoEndpointNotSet = LoggerMessage.Define(
-                eventId: new EventId(22, "UserInfoEndpointNotSet"),
-                logLevel: LogLevel.Debug,
-                formatString: "UserInfoEndpoint is not set. Claims cannot be retrieved.");
-            _unableToProtectNonceCookie = LoggerMessage.Define(
-                eventId: new EventId(23, "UnableToProtectNonceCookie"),
-                logLevel: LogLevel.Warning,
-                formatString: "Failed to un-protect the nonce cookie.");
-            _messageReceived = LoggerMessage.Define<string>(
-                eventId: new EventId(24, "MessageReceived"),
-                logLevel: LogLevel.Trace,
-                formatString: "MessageReceived: '{RedirectUrl}'.");
-            _messageReceivedContextHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(25, "MessageReceivedContextHandledResponse"),
-                logLevel: LogLevel.Debug,
-                formatString: "MessageReceivedContext.HandledResponse");
-            _messageReceivedContextSkipped = LoggerMessage.Define(
-                eventId: new EventId(26, "MessageReceivedContextSkipped"),
-                logLevel: LogLevel.Debug,
-                formatString: "MessageReceivedContext.Skipped");
-            _authorizationCodeReceived = LoggerMessage.Define(
-                eventId: new EventId(27, "AuthorizationCodeReceived"),
-                logLevel: LogLevel.Trace,
-                formatString: "Authorization code received.");
-            _authorizationCodeReceivedContextHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(28, "AuthorizationCodeReceivedContextHandledResponse"),
-                logLevel: LogLevel.Debug,
-                formatString: "AuthorizationCodeReceivedContext.HandledResponse");
-            _authorizationCodeReceivedContextSkipped = LoggerMessage.Define(
-                eventId: new EventId(29, "AuthorizationCodeReceivedContextSkipped"),
-                logLevel: LogLevel.Debug,
-                formatString: "AuthorizationCodeReceivedContext.Skipped");
-            _tokenResponseReceived = LoggerMessage.Define(
-                eventId: new EventId(30, "TokenResponseReceived"),
-                logLevel: LogLevel.Trace,
-                formatString: "Token response received.");
-            _tokenResponseReceivedHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(31, "TokenResponseReceivedHandledResponse"),
-                logLevel: LogLevel.Debug,
-                formatString: "TokenResponseReceived.HandledResponse");
-            _tokenResponseReceivedSkipped = LoggerMessage.Define(
-                eventId: new EventId(32, "TokenResponseReceivedSkipped"),
-                logLevel: LogLevel.Debug,
-                formatString: "TokenResponseReceived.Skipped");
-            _postSignOutRedirect = LoggerMessage.Define<string>(
-                eventId: new EventId(33, "PostSignOutRedirect"),
-                logLevel: LogLevel.Trace,
-                formatString: "Using properties.RedirectUri for redirect post authentication: '{RedirectUri}'.");
-            _userInformationReceived = LoggerMessage.Define<string>(
-                eventId: new EventId(35, "UserInformationReceived"),
-                 logLevel: LogLevel.Trace,
-                formatString: "User information received: {User}");
-            _userInformationReceivedHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(36, "UserInformationReceivedHandledResponse"),
-                logLevel: LogLevel.Debug,
-                formatString: "The UserInformationReceived event returned Handled.");
-            _userInformationReceivedSkipped = LoggerMessage.Define(
-                eventId: new EventId(37, "UserInformationReceivedSkipped"),
-                logLevel: LogLevel.Debug,
-                formatString: "The UserInformationReceived event returned Skipped.");
-            _authenticationFailedContextHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(38, "AuthenticationFailedContextHandledResponse"),
-                logLevel: LogLevel.Debug,
-                formatString: "AuthenticationFailedContext.HandledResponse");
-            _authenticationFailedContextSkipped = LoggerMessage.Define(
-                eventId: new EventId(39, "AuthenticationFailedContextSkipped"),
-                logLevel: LogLevel.Debug,
-                formatString: "AuthenticationFailedContext.Skipped");
-            _invalidSecurityTokenType = LoggerMessage.Define<string?>(
-                eventId: new EventId(40, "InvalidSecurityTokenType"),
-                logLevel: LogLevel.Error,
-                formatString: "The Validated Security Token must be of type JwtSecurityToken, but instead its type is: '{SecurityTokenType}'");
-            _unableToValidateIdToken = LoggerMessage.Define<string>(
-                eventId: new EventId(41, "UnableToValidateIdToken"),
-                logLevel: LogLevel.Error,
-                formatString: "Unable to validate the 'id_token', no suitable ISecurityTokenValidator was found for: '{IdToken}'.");
-            _accessTokenNotAvailable = LoggerMessage.Define(
-                eventId: new EventId(42, "AccessTokenNotAvailable"),
-                logLevel: LogLevel.Debug,
-                formatString: "The access_token is not available. Claims cannot be retrieved.");
-            _unableToReadIdToken = LoggerMessage.Define<string>(
-                eventId: new EventId(43, "UnableToReadIdToken"),
-                logLevel: LogLevel.Error,
-                formatString: "Unable to read the 'id_token', no suitable ISecurityTokenValidator was found for: '{IdToken}'.");
-            _remoteSignOutHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(44, "RemoteSignOutHandledResponse"),
-                logLevel: LogLevel.Debug,
-                formatString: "RemoteSignOutContext.HandledResponse");
-            _remoteSignOutSkipped = LoggerMessage.Define(
-                eventId: new EventId(45, "RemoteSignOutSkipped"),
-                logLevel: LogLevel.Debug,
-                formatString: "RemoteSignOutContext.Skipped");
-            _remoteSignOut = LoggerMessage.Define(
-                eventId: new EventId(46, "RemoteSignOut"),
-                logLevel: LogLevel.Information,
-                formatString: "Remote signout request processed.");
-            _remoteSignOutSessionIdMissing = LoggerMessage.Define(
-                eventId: new EventId(47, "RemoteSignOutSessionIdMissing"),
-                logLevel: LogLevel.Error,
-                formatString: "The remote signout request was ignored because the 'sid' parameter " +
-                             "was missing, which may indicate an unsolicited logout.");
-            _remoteSignOutSessionIdInvalid = LoggerMessage.Define(
-                eventId: new EventId(48, "RemoteSignOutSessionIdInvalid"),
-                logLevel: LogLevel.Error,
-                formatString: "The remote signout request was ignored because the 'sid' parameter didn't match " +
-                             "the expected value, which may indicate an unsolicited logout.");
-            _authenticationSchemeSignedOut = LoggerMessage.Define<string>(
-                eventId: new EventId(49, "AuthenticationSchemeSignedOut"),
-                logLevel: LogLevel.Information,
-                formatString: "AuthenticationScheme: {AuthenticationScheme} signed out.");
-            _signOutCallbackRedirectHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(50, "SignOutCallbackRedirectHandledResponse"),
-                logLevel: LogLevel.Debug,
-                formatString: "RedirectToSignedOutRedirectUri.HandledResponse");
-            _signOutCallbackRedirectSkipped = LoggerMessage.Define(
-                eventId: new EventId(51, "SignOutCallbackRedirectSkipped"),
-                logLevel: LogLevel.Debug,
-                formatString: "RedirectToSignedOutRedirectUri.Skipped");
-
-            //  EventId 52 is used by ResponseErrorWithStatusCode
-            _handleChallenge = LoggerMessage.Define<string, string>(
-                eventId: new EventId(53, "HandleChallenge"),
-                logLevel: LogLevel.Debug,
-                formatString: "HandleChallenge with Location: {Location}; and Set-Cookie: {Cookie}.");
-            _remoteSignOutIssuerMissing = LoggerMessage.Define(
-              eventId: new EventId(54, "RemoteSignOutIssuerMissing"),
-              logLevel: LogLevel.Error,
-              formatString: "The remote signout request was ignored because the 'iss' parameter " +
-                            "was missing, which may indicate an unsolicited logout.");
-            _remoteSignOutIssuerInvalid = LoggerMessage.Define(
-              eventId: new EventId(55, "RemoteSignOutIssuerInvalid"),
-               logLevel: LogLevel.Error,
-               formatString: "The remote signout request was ignored because the 'iss' parameter didn't match " +
-                             "the expected value, which may indicate an unsolicited logout.");
-        }
-
-        public static void UpdatingConfiguration(this ILogger logger)
-        {
-            _updatingConfiguration(logger, null);
-        }
-
-        public static void ConfigurationManagerRequestRefreshCalled(this ILogger logger)
-        {
-            _configurationManagerRequestRefreshCalled(logger, null);
-        }
-
-        public static void AuthorizationCodeReceived(this ILogger logger)
-        {
-            _authorizationCodeReceived(logger, null);
-        }
-
-        public static void TokenResponseReceived(this ILogger logger)
-        {
-            _tokenResponseReceived(logger, null);
-        }
-
-        public static void ReceivedIdToken(this ILogger logger)
-        {
-            _receivedIdToken(logger, null);
-        }
-
-        public static void RedeemingCodeForTokens(this ILogger logger)
-        {
-            _redeemingCodeForTokens(logger, null);
-        }
-
-        public static void TokenValidatedHandledResponse(this ILogger logger)
-        {
-            _tokenValidatedHandledResponse(logger, null);
-        }
-
-        public static void TokenValidatedSkipped(this ILogger logger)
-        {
-            _tokenValidatedSkipped(logger, null);
-        }
-
-        public static void AuthorizationCodeReceivedContextHandledResponse(this ILogger logger)
-        {
-            _authorizationCodeReceivedContextHandledResponse(logger, null);
-        }
-
-        public static void AuthorizationCodeReceivedContextSkipped(this ILogger logger)
-        {
-            _authorizationCodeReceivedContextSkipped(logger, null);
-        }
-
-        public static void TokenResponseReceivedHandledResponse(this ILogger logger)
-        {
-            _tokenResponseReceivedHandledResponse(logger, null);
-        }
-
-        public static void TokenResponseReceivedSkipped(this ILogger logger)
-        {
-            _tokenResponseReceivedSkipped(logger, null);
-        }
-
-        public static void AuthenticationFailedContextHandledResponse(this ILogger logger)
-        {
-            _authenticationFailedContextHandledResponse(logger, null);
-        }
-
-        public static void AuthenticationFailedContextSkipped(this ILogger logger)
-        {
-            _authenticationFailedContextSkipped(logger, null);
-        }
-
-        public static void MessageReceived(this ILogger logger, string redirectUrl)
-        {
-            _messageReceived(logger, redirectUrl, null);
-        }
-
-        public static void MessageReceivedContextHandledResponse(this ILogger logger)
-        {
-            _messageReceivedContextHandledResponse(logger, null);
-        }
-
-        public static void MessageReceivedContextSkipped(this ILogger logger)
-        {
-            _messageReceivedContextSkipped(logger, null);
-        }
-
-        public static void RedirectToIdentityProviderForSignOutHandledResponse(this ILogger logger)
-        {
-            _redirectToIdentityProviderForSignOutHandledResponse(logger, null);
-        }
-
-        public static void RedirectToIdentityProviderHandledResponse(this ILogger logger)
-        {
-            _redirectToIdentityProviderHandledResponse(logger, null);
-        }
-
-        public static void SignOutCallbackRedirectHandledResponse(this ILogger logger)
-        {
-            _signOutCallbackRedirectHandledResponse(logger, null);
-        }
-
-        public static void SignOutCallbackRedirectSkipped(this ILogger logger)
-        {
-            _signOutCallbackRedirectSkipped(logger, null);
-        }
-
-        public static void UserInformationReceivedHandledResponse(this ILogger logger)
-        {
-            _userInformationReceivedHandledResponse(logger, null);
-        }
-
-        public static void UserInformationReceivedSkipped(this ILogger logger)
-        {
-            _userInformationReceivedSkipped(logger, null);
-        }
-
-        public static void InvalidLogoutQueryStringRedirectUrl(this ILogger logger, string redirectUrl)
-        {
-            _invalidLogoutQueryStringRedirectUrl(logger, redirectUrl, null);
-        }
-
-        public static void NullOrEmptyAuthorizationResponseState(this ILogger logger)
-        {
-            _nullOrEmptyAuthorizationResponseState(logger, null);
-        }
-
-        public static void UnableToReadAuthorizationResponseState(this ILogger logger)
-        {
-            _unableToReadAuthorizationResponseState(logger, null);
-        }
-
-        public static void ResponseError(this ILogger logger, string error, string errorDescription, string errorUri)
-        {
-            _responseError(logger, error, errorDescription, errorUri, null);
-        }
-
-        public static void ResponseErrorWithStatusCode(this ILogger logger, string error, string errorDescription, string errorUri, int statusCode)
-        {
-            _responseErrorWithStatusCode(logger, error, errorDescription, errorUri, statusCode, null);
-        }
-
-        public static void ExceptionProcessingMessage(this ILogger logger, Exception ex)
-        {
-            _exceptionProcessingMessage(logger, ex);
-        }
-
-        public static void AccessTokenNotAvailable(this ILogger logger)
-        {
-            _accessTokenNotAvailable(logger, null);
-        }
-
-        public static void RetrievingClaims(this ILogger logger)
-        {
-            _retrievingClaims(logger, null);
-        }
-
-        public static void UserInfoEndpointNotSet(this ILogger logger)
-        {
-            _userInfoEndpointNotSet(logger, null);
-        }
-
-        public static void UnableToProtectNonceCookie(this ILogger logger, Exception ex)
-        {
-            _unableToProtectNonceCookie(logger, ex);
-        }
-
-        public static void InvalidAuthenticationRequestUrl(this ILogger logger, string redirectUri)
-        {
-            _invalidAuthenticationRequestUrl(logger, redirectUri, null);
-        }
-
-        public static void UnableToReadIdToken(this ILogger logger, string idToken)
-        {
-            _unableToReadIdToken(logger, idToken, null);
-        }
-
-        public static void InvalidSecurityTokenType(this ILogger logger, string? tokenType)
-        {
-            _invalidSecurityTokenType(logger, tokenType, null);
-        }
-
-        public static void UnableToValidateIdToken(this ILogger logger, string idToken)
-        {
-            _unableToValidateIdToken(logger, idToken, null);
-        }
-
-        public static void EnteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync(this ILogger logger, string openIdConnectHandlerTypeName)
-        {
-            _enteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync(logger, openIdConnectHandlerTypeName, null);
-        }
-
-        public static void EnteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync(this ILogger logger, string openIdConnectHandlerTypeName)
-        {
-            _enteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync(logger, openIdConnectHandlerTypeName, null);
-        }
-
-        public static void EnteringOpenIdAuthenticationHandlerHandleSignOutAsync(this ILogger logger, string openIdConnectHandlerTypeName)
-        {
-            _enteringOpenIdAuthenticationHandlerHandleSignOutAsync(logger, openIdConnectHandlerTypeName, null);
-        }
-
-        public static void UserInformationReceived(this ILogger logger, string user)
-        {
-            _userInformationReceived(logger, user, null);
-        }
-
-        public static void PostAuthenticationLocalRedirect(this ILogger logger, string redirectUri)
-        {
-            _postAuthenticationLocalRedirect(logger, redirectUri, null);
-        }
-
-        public static void PostSignOutRedirect(this ILogger logger, string redirectUri)
-        {
-            _postSignOutRedirect(logger, redirectUri, null);
-        }
-
-        public static void RemoteSignOutHandledResponse(this ILogger logger)
-        {
-            _remoteSignOutHandledResponse(logger, null);
-        }
-
-        public static void RemoteSignOutSkipped(this ILogger logger)
-        {
-            _remoteSignOutSkipped(logger, null);
-        }
-
-        public static void RemoteSignOut(this ILogger logger)
-        {
-            _remoteSignOut(logger, null);
-        }
-
-        public static void RemoteSignOutSessionIdMissing(this ILogger logger)
-        {
-            _remoteSignOutSessionIdMissing(logger, null);
-        }
-
-        public static void RemoteSignOutSessionIdInvalid(this ILogger logger)
-        {
-            _remoteSignOutSessionIdInvalid(logger, null);
-        }
-
-        public static void AuthenticationSchemeSignedOut(this ILogger logger, string authenticationScheme)
-        {
-            _authenticationSchemeSignedOut(logger, authenticationScheme, null);
-        }
-
-        public static void HandleChallenge(this ILogger logger, string location, string cookie)
-            => _handleChallenge(logger, location, cookie, null);
-
-        public static void RemoteSignOutIssuerMissing(this ILogger logger)
-        {
-            _remoteSignOutIssuerMissing(logger, null);
-        }
-
-        public static void RemoteSignOutIssuerInvalid(this ILogger logger)
-        {
-            _remoteSignOutIssuerInvalid(logger, null);
-        }
+        [LoggerMessage(13, LogLevel.Debug, "Updating configuration", EventName = "UpdatingConfiguration")]
+        public static partial void UpdatingConfiguration(this ILogger logger);
+
+        [LoggerMessage(18, LogLevel.Debug, "Exception of type 'SecurityTokenSignatureKeyNotFoundException' thrown, Options.ConfigurationManager.RequestRefresh() called.", EventName = "ConfigurationManagerRequestRefreshCalled")]
+        public static partial void ConfigurationManagerRequestRefreshCalled(this ILogger logger);
+
+        [LoggerMessage(27, LogLevel.Trace, "Authorization code received.", EventName = "AuthorizationCodeReceived")]
+        public static partial void AuthorizationCodeReceived(this ILogger logger);
+
+        [LoggerMessage(30, LogLevel.Trace, "Token response received.", EventName = "TokenResponseReceived")]
+        public static partial void TokenResponseReceived(this ILogger logger);
+
+        [LoggerMessage(21, LogLevel.Debug, "Received 'id_token'", EventName = "ReceivedIdToken")]
+        public static partial void ReceivedIdToken(this ILogger logger);
+
+        [LoggerMessage(19, LogLevel.Debug, "Redeeming code for tokens.", EventName = "RedeemingCodeForTokens")]
+        public static partial void RedeemingCodeForTokens(this ILogger logger);
+
+        [LoggerMessage(15, LogLevel.Debug, "TokenValidated.HandledResponse", EventName = "TokenValidatedHandledResponse")]
+        public static partial void TokenValidatedHandledResponse(this ILogger logger);
+
+        [LoggerMessage(16, LogLevel.Debug, "TokenValidated.Skipped", EventName = "TokenValidatedSkipped")]
+        public static partial void TokenValidatedSkipped(this ILogger logger);
+
+        [LoggerMessage(28, LogLevel.Debug, "AuthorizationCodeReceivedContext.HandledResponse", EventName = "AuthorizationCodeReceivedContextHandledResponse")]
+        public static partial void AuthorizationCodeReceivedContextHandledResponse(this ILogger logger);
+
+        [LoggerMessage(29, LogLevel.Debug, "AuthorizationCodeReceivedContext.Skipped", EventName = "AuthorizationCodeReceivedContextSkipped")]
+        public static partial void AuthorizationCodeReceivedContextSkipped(this ILogger logger);
+
+        [LoggerMessage(31, LogLevel.Debug, "TokenResponseReceived.HandledResponse", EventName = "TokenResponseReceivedHandledResponse")]
+        public static partial void TokenResponseReceivedHandledResponse(this ILogger logger);
+
+        [LoggerMessage(32, LogLevel.Debug, "TokenResponseReceived.Skipped", EventName = "TokenResponseReceivedSkipped")]
+        public static partial void TokenResponseReceivedSkipped(this ILogger logger);
+
+        [LoggerMessage(38, LogLevel.Debug, "AuthenticationFailedContext.HandledResponse", EventName = "AuthenticationFailedContextHandledResponse")]
+        public static partial void AuthenticationFailedContextHandledResponse(this ILogger logger);
+
+        [LoggerMessage(39, LogLevel.Debug, "AuthenticationFailedContext.Skipped", EventName = "AuthenticationFailedContextSkipped")]
+        public static partial void AuthenticationFailedContextSkipped(this ILogger logger);
+
+        [LoggerMessage(24, LogLevel.Trace, "MessageReceived: '{RedirectUrl}'.", EventName = "MessageReceived")]
+        public static partial void MessageReceived(this ILogger logger, string redirectUrl);
+
+        [LoggerMessage(25, LogLevel.Debug, "MessageReceivedContext.HandledResponse", EventName = "MessageReceivedContextHandledResponse")]
+        public static partial void MessageReceivedContextHandledResponse(this ILogger logger);
+
+        [LoggerMessage(26, LogLevel.Debug, "MessageReceivedContext.Skipped", EventName = "MessageReceivedContextSkipped")]
+        public static partial void MessageReceivedContextSkipped(this ILogger logger);
+
+        [LoggerMessage(1, LogLevel.Debug, "RedirectToIdentityProviderForSignOut.HandledResponse", EventName = "RedirectToIdentityProviderForSignOutHandledResponse")]
+        public static partial void RedirectToIdentityProviderForSignOutHandledResponse(this ILogger logger);
+
+        [LoggerMessage(6, LogLevel.Debug, "RedirectToIdentityProvider.HandledResponse", EventName = "RedirectToIdentityProviderHandledResponse")]
+        public static partial void RedirectToIdentityProviderHandledResponse(this ILogger logger);
+
+        [LoggerMessage(50, LogLevel.Debug, "RedirectToSignedOutRedirectUri.HandledResponse", EventName = "SignOutCallbackRedirectHandledResponse")]
+        public static partial void SignOutCallbackRedirectHandledResponse(this ILogger logger);
+
+        [LoggerMessage(51, LogLevel.Debug, "RedirectToSignedOutRedirectUri.Skipped", EventName = "SignOutCallbackRedirectSkipped")]
+        public static partial void SignOutCallbackRedirectSkipped(this ILogger logger);
+
+        [LoggerMessage(36, LogLevel.Debug, "The UserInformationReceived event returned Handled.", EventName = "UserInformationReceivedHandledResponse")]
+        public static partial void UserInformationReceivedHandledResponse(this ILogger logger);
+
+        [LoggerMessage(37, LogLevel.Debug, "The UserInformationReceived event returned Skipped.", EventName = "UserInformationReceivedSkipped")]
+        public static partial void UserInformationReceivedSkipped(this ILogger logger);
+
+        [LoggerMessage(3, LogLevel.Warning, "The query string for Logout is not a well-formed URI. Redirect URI: '{RedirectUrl}'.", EventName = "InvalidLogoutQueryStringRedirectUrl")]
+        public static partial void InvalidLogoutQueryStringRedirectUrl(this ILogger logger, string redirectUrl);
+
+        [LoggerMessage(10, LogLevel.Debug, "message.State is null or empty.", EventName = "NullOrEmptyAuthorizationResponseState")]
+        public static partial void NullOrEmptyAuthorizationResponseState(this ILogger logger);
+
+        [LoggerMessage(11, LogLevel.Debug, "Unable to read the message.State.", EventName = "UnableToReadAuthorizationResponseState")]
+        public static partial void UnableToReadAuthorizationResponseState(this ILogger logger);
+
+        [LoggerMessage(12, LogLevel.Error, "Message contains error: '{Error}', error_description: '{ErrorDescription}', error_uri: '{ErrorUri}'.", EventName = "ResponseError")]
+        public static partial void ResponseError(this ILogger logger, string error, string errorDescription, string errorUri);
+
+        [LoggerMessage(52, LogLevel.Error, "Message contains error: '{Error}', error_description: '{ErrorDescription}', error_uri: '{ErrorUri}', status code '{StatusCode}'.", EventName = "ResponseErrorWithStatusCode")]
+        public static partial void ResponseErrorWithStatusCode(this ILogger logger, string error, string errorDescription, string errorUri, int statusCode);
+
+        [LoggerMessage(17, LogLevel.Error, "Exception occurred while processing message.", EventName = "ExceptionProcessingMessage")]
+        public static partial void ExceptionProcessingMessage(this ILogger logger, Exception ex);
+
+        [LoggerMessage(42, LogLevel.Debug, "The access_token is not available. Claims cannot be retrieved.", EventName = "AccessTokenNotAvailable")]
+        public static partial void AccessTokenNotAvailable(this ILogger logger);
+
+        [LoggerMessage(20, LogLevel.Trace, "Retrieving claims from the user info endpoint.", EventName = "RetrievingClaims")]
+        public static partial void RetrievingClaims(this ILogger logger);
+
+        [LoggerMessage(22, LogLevel.Debug, "UserInfoEndpoint is not set. Claims cannot be retrieved.", EventName = "UserInfoEndpointNotSet")]
+        public static partial void UserInfoEndpointNotSet(this ILogger logger);
+
+        [LoggerMessage(23, LogLevel.Warning, "Failed to un-protect the nonce cookie.", EventName = "UnableToProtectNonceCookie")]
+        public static partial void UnableToProtectNonceCookie(this ILogger logger, Exception ex);
+
+        [LoggerMessage(8, LogLevel.Warning, "The redirect URI is not well-formed. The URI is: '{AuthenticationRequestUrl}'.", EventName = "InvalidAuthenticationRequestUrl")]
+        public static partial void InvalidAuthenticationRequestUrl(this ILogger logger, string authenticationRequestUrl);
+
+        [LoggerMessage(43, LogLevel.Error, "Unable to read the 'id_token', no suitable ISecurityTokenValidator was found for: '{IdToken}'.", EventName = "UnableToReadIdToken")]
+        public static partial void UnableToReadIdToken(this ILogger logger, string idToken);
+
+        [LoggerMessage(40, LogLevel.Error, "The Validated Security Token must be of type JwtSecurityToken, but instead its type is: '{SecurityTokenType}'", EventName = "InvalidSecurityTokenType")]
+        public static partial void InvalidSecurityTokenType(this ILogger logger, string? securityTokenType);
+
+        [LoggerMessage(41, LogLevel.Error, "Unable to validate the 'id_token', no suitable ISecurityTokenValidator was found for: '{IdToken}'.", EventName = "UnableToValidateIdToken")]
+        public static partial void UnableToValidateIdToken(this ILogger logger, string idToken);
+
+        [LoggerMessage(9, LogLevel.Trace, "Entering {OpenIdConnectHandlerType}'s HandleRemoteAuthenticateAsync.", EventName = "EnteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync")]
+        public static partial void EnteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync(this ILogger logger, string openIdConnectHandlerType);
+
+        [LoggerMessage(4, LogLevel.Trace, "Entering {OpenIdConnectHandlerType}'s HandleUnauthorizedAsync.", EventName = "EnteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync")]
+        public static partial void EnteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync(this ILogger logger, string openIdConnectHandlerType);
+
+        [LoggerMessage(14, LogLevel.Trace, "Entering {OpenIdConnectHandlerType}'s HandleSignOutAsync.", EventName = "EnteringOpenIdAuthenticationHandlerHandleSignOutAsync")]
+        public static partial void EnteringOpenIdAuthenticationHandlerHandleSignOutAsync(this ILogger logger, string openIdConnectHandlerType);
+
+        [LoggerMessage(35, LogLevel.Trace, "User information received: {User}", EventName = "UserInformationReceived")]
+        public static partial void UserInformationReceived(this ILogger logger, string user);
+
+        [LoggerMessage(5, LogLevel.Trace, "Using properties.RedirectUri for 'local redirect' post authentication: '{RedirectUri}'.", EventName = "PostAuthenticationLocalRedirect")]
+        public static partial void PostAuthenticationLocalRedirect(this ILogger logger, string redirectUri);
+
+        [LoggerMessage(33, LogLevel.Trace, "Using properties.RedirectUri for redirect post authentication: '{RedirectUri}'.", EventName = "PostSignOutRedirect")]
+        public static partial void PostSignOutRedirect(this ILogger logger, string redirectUri);
+
+        [LoggerMessage(44, LogLevel.Debug, "RemoteSignOutContext.HandledResponse", EventName = "RemoteSignOutHandledResponse")]
+        public static partial void RemoteSignOutHandledResponse(this ILogger logger);
+
+        [LoggerMessage(45, LogLevel.Debug, "RemoteSignOutContext.Skipped", EventName = "RemoteSignOutSkipped")]
+        public static partial void RemoteSignOutSkipped(this ILogger logger);
+
+        [LoggerMessage(46, LogLevel.Information, "Remote signout request processed.", EventName = "RemoteSignOut")]
+        public static partial void RemoteSignOut(this ILogger logger);
+
+        [LoggerMessage(47, LogLevel.Error, "The remote signout request was ignored because the 'sid' parameter " +
+                             "was missing, which may indicate an unsolicited logout.", EventName = "RemoteSignOutSessionIdMissing")]
+        public static partial void RemoteSignOutSessionIdMissing(this ILogger logger);
+
+        [LoggerMessage(48, LogLevel.Error, "The remote signout request was ignored because the 'sid' parameter didn't match " +
+                             "the expected value, which may indicate an unsolicited logout.", EventName = "RemoteSignOutSessionIdInvalid")]
+        public static partial void RemoteSignOutSessionIdInvalid(this ILogger logger);
+
+        [LoggerMessage(49, LogLevel.Information, "AuthenticationScheme: {AuthenticationScheme} signed out.", EventName = "AuthenticationSchemeSignedOut")]
+        public static partial void AuthenticationSchemeSignedOut(this ILogger logger, string authenticationScheme);
+
+        [LoggerMessage(53, LogLevel.Debug, "HandleChallenge with Location: {Location}; and Set-Cookie: {Cookie}.", EventName = "HandleChallenge")]
+        public static partial void HandleChallenge(this ILogger logger, string location, string cookie);
+
+        [LoggerMessage(54, LogLevel.Error, "The remote signout request was ignored because the 'iss' parameter " +
+                            "was missing, which may indicate an unsolicited logout.", EventName = "RemoteSignOutIssuerMissing")]
+        public static partial void RemoteSignOutIssuerMissing(this ILogger logger);
+
+        [LoggerMessage(55, LogLevel.Error, "The remote signout request was ignored because the 'iss' parameter didn't match " +
+                             "the expected value, which may indicate an unsolicited logout.", EventName = "RemoteSignOutIssuerInvalid")]
+        public static partial void RemoteSignOutIssuerInvalid(this ILogger logger);
     }
 }

+ 7 - 35
src/Security/Authentication/Twitter/src/LoggingExtensions.cs

@@ -1,46 +1,18 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
-
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, Exception?> _obtainRequestToken;
-        private static readonly Action<ILogger, Exception?> _obtainAccessToken;
-        private static readonly Action<ILogger, Exception?> _retrieveUserDetails;
-
-        static LoggingExtensions()
-        {
-            _obtainRequestToken = LoggerMessage.Define(
-                eventId: new EventId(1, "ObtainRequestToken"),
-                logLevel: LogLevel.Debug,
-                formatString: "ObtainRequestToken");
-            _obtainAccessToken = LoggerMessage.Define(
-                eventId: new EventId(2, "ObtainAccessToken"),
-                logLevel: LogLevel.Debug,
-                formatString: "ObtainAccessToken");
-            _retrieveUserDetails = LoggerMessage.Define(
-                eventId: new EventId(3, "RetrieveUserDetails"),
-                logLevel: LogLevel.Debug,
-                formatString: "RetrieveUserDetails");
-
-        }
 
-        public static void ObtainAccessToken(this ILogger logger)
-        {
-            _obtainAccessToken(logger, null);
-        }
+        [LoggerMessage(2, LogLevel.Debug, "ObtainAccessToken", EventName = "ObtainAccessToken")]
+        public static partial void ObtainAccessToken(this ILogger logger);
 
-        public static void ObtainRequestToken(this ILogger logger)
-        {
-            _obtainRequestToken(logger, null);
-        }
+        [LoggerMessage(1, LogLevel.Debug, "ObtainRequestToken", EventName = "ObtainRequestToken")]
+        public static partial void ObtainRequestToken(this ILogger logger);
 
-        public static void RetrieveUserDetails(this ILogger logger)
-        {
-            _retrieveUserDetails(logger, null);
-        }
+        [LoggerMessage(3, LogLevel.Debug, "RetrieveUserDetails", EventName = "RetrieveUserDetails")]
+        public static partial void RetrieveUserDetails(this ILogger logger);
     }
 }

+ 15 - 69
src/Security/Authentication/WsFederation/src/LoggingExtensions.cs

@@ -5,81 +5,27 @@ using System;
 
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, Exception?> _signInWithoutWResult;
-        private static readonly Action<ILogger, Exception?> _signInWithoutToken;
-        private static readonly Action<ILogger, Exception> _exceptionProcessingMessage;
-        private static readonly Action<ILogger, string, Exception?> _malformedRedirectUri;
-        private static readonly Action<ILogger, Exception?> _remoteSignOutHandledResponse;
-        private static readonly Action<ILogger, Exception?> _remoteSignOutSkipped;
-        private static readonly Action<ILogger, Exception?> _remoteSignOut;
+        [LoggerMessage(1, LogLevel.Debug, "Received a sign-in message without a WResult.", EventName = "SignInWithoutWResult")]
+        public static partial void SignInWithoutWResult(this ILogger logger);
 
-        static LoggingExtensions()
-        {
-            _signInWithoutWResult = LoggerMessage.Define(
-                eventId: new EventId(1, "SignInWithoutWResult"),
-                logLevel: LogLevel.Debug,
-                formatString: "Received a sign-in message without a WResult.");
-            _signInWithoutToken = LoggerMessage.Define(
-                eventId: new EventId(2, "SignInWithoutToken"),
-                logLevel: LogLevel.Debug,
-                formatString: "Received a sign-in message without a token.");
-            _exceptionProcessingMessage = LoggerMessage.Define(
-                eventId: new EventId(3, "ExceptionProcessingMessage"),
-                logLevel: LogLevel.Error,
-                formatString: "Exception occurred while processing message.");
-            _malformedRedirectUri = LoggerMessage.Define<string>(
-                eventId: new EventId(4, "MalformedRedirectUri"),
-                logLevel: LogLevel.Warning,
-                formatString: "The sign-out redirect URI '{0}' is malformed.");
-            _remoteSignOutHandledResponse = LoggerMessage.Define(
-                eventId: new EventId(5, "RemoteSignOutHandledResponse"),
-               logLevel: LogLevel.Debug,
-               formatString: "RemoteSignOutContext.HandledResponse");
-            _remoteSignOutSkipped = LoggerMessage.Define(
-                eventId: new EventId(6, "RemoteSignOutSkipped"),
-               logLevel: LogLevel.Debug,
-               formatString: "RemoteSignOutContext.Skipped");
-            _remoteSignOut = LoggerMessage.Define(
-                eventId: new EventId(7, "RemoteSignOut"),
-               logLevel: LogLevel.Information,
-               formatString: "Remote signout request processed.");
-        }
+        [LoggerMessage(2, LogLevel.Debug, "Received a sign-in message without a token.", EventName = "SignInWithoutToken")]
+        public static partial void SignInWithoutToken(this ILogger logger);
 
-        public static void SignInWithoutWResult(this ILogger logger)
-        {
-            _signInWithoutWResult(logger, null);
-        }
+        [LoggerMessage(3, LogLevel.Error, "Exception occurred while processing message.", EventName = "ExceptionProcessingMessage")]
+        public static partial void ExceptionProcessingMessage(this ILogger logger, Exception ex);
 
-        public static void SignInWithoutToken(this ILogger logger)
-        {
-            _signInWithoutToken(logger, null);
-        }
+        [LoggerMessage(4, LogLevel.Warning, "The sign-out redirect URI '{uri}' is malformed.", EventName = "MalformedRedirectUri")]
+        public static partial void MalformedRedirectUri(this ILogger logger, string uri);
 
-        public static void ExceptionProcessingMessage(this ILogger logger, Exception ex)
-        {
-            _exceptionProcessingMessage(logger, ex);
-        }
+        [LoggerMessage(5, LogLevel.Debug, "RemoteSignOutContext.HandledResponse", EventName = "RemoteSignOutHandledResponse")]
+        public static partial void RemoteSignOutHandledResponse(this ILogger logger);
 
-        public static void MalformedRedirectUri(this ILogger logger, string uri)
-        {
-            _malformedRedirectUri(logger, uri, null);
-        }
+        [LoggerMessage(6, LogLevel.Debug, "RemoteSignOutContext.Skipped", EventName = "RemoteSignOutSkipped")]
+        public static partial void RemoteSignOutSkipped(this ILogger logger);
 
-        public static void RemoteSignOutHandledResponse(this ILogger logger)
-        {
-            _remoteSignOutHandledResponse(logger, null);
-        }
-
-        public static void RemoteSignOutSkipped(this ILogger logger)
-        {
-            _remoteSignOutSkipped(logger, null);
-        }
-
-        public static void RemoteSignOut(this ILogger logger)
-        {
-            _remoteSignOut(logger, null);
-        }
+        [LoggerMessage(7, LogLevel.Information, "Remote signout request processed.", EventName = "RemoteSignOut")]
+        public static partial void RemoteSignOut(this ILogger logger);
     }
 }

+ 6 - 13
src/Security/Authorization/Core/src/LoggingExtensions.cs

@@ -6,20 +6,13 @@ using Microsoft.AspNetCore.Authorization;
 
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, string, Exception?> _userAuthorizationFailed = LoggerMessage.Define<string>(
-            eventId: new EventId(2, "UserAuthorizationFailed"),
-            logLevel: LogLevel.Information,
-            formatString: "Authorization failed. {0}");
+        [LoggerMessage(1, LogLevel.Debug, "Authorization was successful.", EventName = "UserAuthorizationSucceeded")]
+        public static partial void UserAuthorizationSucceeded(this ILogger logger);
 
-        private static readonly Action<ILogger, Exception?> _userAuthorizationSucceeded = LoggerMessage.Define(
-            eventId: new EventId(1, "UserAuthorizationSucceeded"),
-            logLevel: LogLevel.Debug,
-            formatString: "Authorization was successful.");
-
-        public static void UserAuthorizationSucceeded(this ILogger logger)
-            => _userAuthorizationSucceeded(logger, null);
+        [LoggerMessage(2, LogLevel.Information, "Authorization failed. {Reason}", EventName = "UserAuthorizationFailed")]
+        private static partial void UserAuthorizationFailed(this ILogger logger, string reason);
 
         public static void UserAuthorizationFailed(this ILogger logger, AuthorizationFailure failure)
         {
@@ -27,7 +20,7 @@ namespace Microsoft.Extensions.Logging
                 ? "Fail() was explicitly called."
                 : "These requirements were not met:" + Environment.NewLine + string.Join(Environment.NewLine, failure.FailedRequirements);
 
-            _userAuthorizationFailed(logger, reason, null);
+            UserAuthorizationFailed(logger, reason);
         }
     }
 }

+ 19 - 89
src/Security/CookiePolicy/src/LoggingExtensions.cs

@@ -1,105 +1,35 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
-
 namespace Microsoft.Extensions.Logging
 {
-    internal static class LoggingExtensions
+    internal static partial class LoggingExtensions
     {
-        private static readonly Action<ILogger, bool, Exception?> _needsConsent;
-        private static readonly Action<ILogger, bool, Exception?> _hasConsent;
-        private static readonly Action<ILogger, Exception?> _consentGranted;
-        private static readonly Action<ILogger, Exception?> _consentWithdrawn;
-        private static readonly Action<ILogger, string, Exception?> _cookieSuppressed;
-        private static readonly Action<ILogger, string, Exception?> _deleteCookieSuppressed;
-        private static readonly Action<ILogger, string, Exception?> _upgradedToSecure;
-        private static readonly Action<ILogger, string, string, Exception?> _upgradedSameSite;
-        private static readonly Action<ILogger, string, Exception?> _upgradedToHttpOnly;
-
-        static LoggingExtensions()
-        {
-            _needsConsent = LoggerMessage.Define<bool>(
-                eventId: new EventId(1, "NeedsConsent"),
-                logLevel: LogLevel.Trace,
-                formatString: "Needs consent: {needsConsent}.");
-            _hasConsent = LoggerMessage.Define<bool>(
-                eventId: new EventId(2, "HasConsent"),
-                logLevel: LogLevel.Trace,
-                formatString: "Has consent: {hasConsent}.");
-            _consentGranted = LoggerMessage.Define(
-                eventId: new EventId(3, "ConsentGranted"),
-                logLevel: LogLevel.Debug,
-                formatString: "Consent granted.");
-            _consentWithdrawn = LoggerMessage.Define(
-                eventId: new EventId(4, "ConsentWithdrawn"),
-                logLevel: LogLevel.Debug,
-                formatString: "Consent withdrawn.");
-            _cookieSuppressed = LoggerMessage.Define<string>(
-                eventId: new EventId(5, "CookieSuppressed"),
-                logLevel: LogLevel.Debug,
-                formatString: "Cookie '{key}' suppressed due to consent policy.");
-            _deleteCookieSuppressed = LoggerMessage.Define<string>(
-                eventId: new EventId(6, "DeleteCookieSuppressed"),
-                logLevel: LogLevel.Debug,
-                formatString: "Delete cookie '{key}' suppressed due to developer policy.");
-            _upgradedToSecure = LoggerMessage.Define<string>(
-                eventId: new EventId(7, "UpgradedToSecure"),
-                logLevel: LogLevel.Debug,
-                formatString: "Cookie '{key}' upgraded to 'secure'.");
-            _upgradedSameSite = LoggerMessage.Define<string, string>(
-                eventId: new EventId(8, "UpgradedSameSite"),
-                logLevel: LogLevel.Debug,
-                formatString: "Cookie '{key}' same site mode upgraded to '{mode}'.");
-            _upgradedToHttpOnly = LoggerMessage.Define<string>(
-                eventId: new EventId(9, "UpgradedToHttpOnly"),
-                logLevel: LogLevel.Debug,
-                formatString: "Cookie '{key}' upgraded to 'httponly'.");
-        }
-
-        public static void NeedsConsent(this ILogger logger, bool needsConsent)
-        {
-            _needsConsent(logger, needsConsent, null);
-        }
+        [LoggerMessage(1, LogLevel.Trace, "Needs consent: {needsConsent}.", EventName = "NeedsConsent")]
+        public static partial void NeedsConsent(this ILogger logger, bool needsConsent);
 
-        public static void HasConsent(this ILogger logger, bool hasConsent)
-        {
-            _hasConsent(logger, hasConsent, null);
-        }
+        [LoggerMessage(2, LogLevel.Trace, "Has consent: {hasConsent}.", EventName = "HasConsent")]
+        public static partial void HasConsent(this ILogger logger, bool hasConsent);
 
-        public static void ConsentGranted(this ILogger logger)
-        {
-            _consentGranted(logger, null);
-        }
+        [LoggerMessage(3, LogLevel.Debug, "Consent granted.", EventName = "ConsentGranted")]
+        public static partial void ConsentGranted(this ILogger logger);
 
-        public static void ConsentWithdrawn(this ILogger logger)
-        {
-            _consentWithdrawn(logger, null);
-        }
+        [LoggerMessage(4, LogLevel.Debug, "Consent withdrawn.", EventName = "ConsentWithdrawn")]
+        public static partial void ConsentWithdrawn(this ILogger logger);
 
-        public static void CookieSuppressed(this ILogger logger, string key)
-        {
-            _cookieSuppressed(logger, key, null);
-        }
+        [LoggerMessage(5, LogLevel.Debug, "Cookie '{key}' suppressed due to consent policy.", EventName = "CookieSuppressed")]
+        public static partial void CookieSuppressed(this ILogger logger, string key);
 
-        public static void DeleteCookieSuppressed(this ILogger logger, string key)
-        {
-            _deleteCookieSuppressed(logger, key, null);
-        }
+        [LoggerMessage(6, LogLevel.Debug, "Delete cookie '{key}' suppressed due to developer policy.", EventName = "DeleteCookieSuppressed")]
+        public static partial void DeleteCookieSuppressed(this ILogger logger, string key);
 
-        public static void CookieUpgradedToSecure(this ILogger logger, string key)
-        {
-            _upgradedToSecure(logger, key, null);
-        }
+        [LoggerMessage(7, LogLevel.Debug, "Cookie '{key}' upgraded to 'secure'.", EventName = "UpgradedToSecure")]
+        public static partial void CookieUpgradedToSecure(this ILogger logger, string key);
 
-        public static void CookieSameSiteUpgraded(this ILogger logger, string key, string mode)
-        {
-            _upgradedSameSite(logger, key, mode, null);
-        }
+        [LoggerMessage(8, LogLevel.Debug, "Cookie '{key}' same site mode upgraded to '{mode}'.", EventName = "UpgradedSameSite")]
+        public static partial void CookieSameSiteUpgraded(this ILogger logger, string key, string mode);
 
-        public static void CookieUpgradedToHttpOnly(this ILogger logger, string key)
-        {
-            _upgradedToHttpOnly(logger, key, null);
-        }
+        [LoggerMessage(9, LogLevel.Debug, "Cookie '{key}' upgraded to 'httponly'.", EventName = "UpgradedToHttpOnly")]
+        public static partial void CookieUpgradedToHttpOnly(this ILogger logger, string key);
     }
 }

+ 3 - 16
src/Shared/StackTrace/ExceptionDetails/LoggerExtensions.cs

@@ -1,26 +1,13 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System;
 using Microsoft.Extensions.Logging;
 
 namespace Microsoft.Extensions.StackTrace.Sources
 {
-    internal static class LoggerExtensions
+    internal static partial class LoggerExtensions
     {
-        private static readonly Action<ILogger, Exception> _failedToReadStackFrameInfo;
-
-        static LoggerExtensions()
-        {
-            _failedToReadStackFrameInfo = LoggerMessage.Define(
-                logLevel: LogLevel.Debug,
-                eventId: new EventId(0, "FailedToReadStackTraceInfo"),
-                formatString: "Failed to read stack trace information for exception.");
-        }
-
-        public static void FailedToReadStackTraceInfo(this ILogger logger, Exception exception)
-        {
-            _failedToReadStackFrameInfo(logger, exception);
-        }
+        [LoggerMessage(0, LogLevel.Debug, "Failed to read stack trace information for exception.", EventName = "FailedToReadStackTraceInfo")]
+        public static partial void FailedToReadStackTraceInfo(this ILogger logger, Exception exception);
     }
 }