From de9a82fe8eae0d40b70edbe04a766e3ac0ad8d54 Mon Sep 17 00:00:00 2001 From: Noam Greenberg <106929496+wabalubdub@users.noreply.github.com> Date: Thu, 12 Sep 2024 17:31:10 +0300 Subject: [PATCH] Update logging to use generated logs (#2531) --- .../GrpcHealthChecksPublisher.cs | 21 +- .../ContextPropagationInterceptor.cs | 13 +- .../GrpcReflectionServiceExtensions.cs | 11 +- .../Internal/GrpcServerLog.cs | 254 ++++-------------- .../Internal/ServerCallHandlerFactory.cs | 20 +- .../Internal/BinderServiceModelProvider.cs | 11 +- .../Model/Internal/ServiceRouteBuilder.cs | 26 +- .../Internal/GrpcWebMiddleware.cs | 33 +-- src/Grpc.Net.Client/Balancer/DnsResolver.cs | 44 +-- .../Balancer/Internal/BalancerHttpHandler.cs | 18 +- .../Balancer/Internal/ConnectionManager.cs | 116 ++------ .../SocketConnectivitySubchannelTransport.cs | 155 +++-------- .../Balancer/PickFirstBalancer.cs | 17 +- .../Balancer/PollingResolver.cs | 66 ++--- src/Grpc.Net.Client/Balancer/Subchannel.cs | 177 ++++-------- .../Balancer/SubchannelsLoadBalancer.cs | 52 ++-- src/Grpc.Net.Client/GrpcChannel.cs | 13 +- .../Internal/ClientStreamWriterBase.cs | 29 +- src/Grpc.Net.Client/Internal/GrpcCallLog.cs | 238 ++++------------ .../Internal/HttpContentClientStreamReader.cs | 11 +- .../Internal/Retry/ChannelRetryThrottling.cs | 13 +- .../Internal/Retry/RetryCallBaseLog.cs | 121 ++------- .../Internal/GrpcCallInvokerFactory.cs | 13 +- 23 files changed, 384 insertions(+), 1088 deletions(-) diff --git a/src/Grpc.AspNetCore.HealthChecks/GrpcHealthChecksPublisher.cs b/src/Grpc.AspNetCore.HealthChecks/GrpcHealthChecksPublisher.cs index 36ecd8a28..7fee5bfe5 100644 --- a/src/Grpc.AspNetCore.HealthChecks/GrpcHealthChecksPublisher.cs +++ b/src/Grpc.AspNetCore.HealthChecks/GrpcHealthChecksPublisher.cs @@ -25,7 +25,7 @@ namespace Grpc.AspNetCore.HealthChecks; -internal sealed class GrpcHealthChecksPublisher : IHealthCheckPublisher +internal sealed partial class GrpcHealthChecksPublisher : IHealthCheckPublisher { private readonly HealthServiceImpl _healthService; private readonly ILogger _logger; @@ -75,22 +75,13 @@ public Task PublishAsync(HealthReport report, CancellationToken cancellationToke return Task.CompletedTask; } - private static class Log + private static partial class Log { - private static readonly Action _evaluatingPublishedHealthReport = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "EvaluatingPublishedHealthReport"), "Evaluating {HealthReportEntryCount} published health report entries against {ServiceMappingCount} service mappings."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "EvaluatingPublishedHealthReport", Message = "Evaluating {HealthReportEntryCount} published health report entries against {ServiceMappingCount} service mappings.")] + public static partial void EvaluatingPublishedHealthReport(ILogger logger, int healthReportEntryCount, int serviceMappingCount); - private static readonly Action _serviceMappingStatusUpdated = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "ServiceMappingStatusUpdated"), "Service '{ServiceName}' status updated to {Status}. {EntriesCount} health report entries evaluated."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "ServiceMappingStatusUpdated", Message = "Service '{ServiceName}' status updated to {Status}. {EntriesCount} health report entries evaluated.")] + public static partial void ServiceMappingStatusUpdated(ILogger logger, string serviceName, HealthCheckResponse.Types.ServingStatus status, int entriesCount); - public static void EvaluatingPublishedHealthReport(ILogger logger, int healthReportEntryCount, int serviceMappingCount) - { - _evaluatingPublishedHealthReport(logger, healthReportEntryCount, serviceMappingCount, null); - } - - public static void ServiceMappingStatusUpdated(ILogger logger, string serviceName, HealthCheckResponse.Types.ServingStatus status, int entriesCount) - { - _serviceMappingStatusUpdated(logger, serviceName, status, entriesCount, null); - } } } diff --git a/src/Grpc.AspNetCore.Server.ClientFactory/ContextPropagationInterceptor.cs b/src/Grpc.AspNetCore.Server.ClientFactory/ContextPropagationInterceptor.cs index d2baa257b..651996b96 100644 --- a/src/Grpc.AspNetCore.Server.ClientFactory/ContextPropagationInterceptor.cs +++ b/src/Grpc.AspNetCore.Server.ClientFactory/ContextPropagationInterceptor.cs @@ -30,7 +30,7 @@ namespace Grpc.AspNetCore.ClientFactory; /// The interceptor gets the request from IHttpContextAccessor, which is a singleton. /// IHttpContextAccessor uses an async local value. /// -internal class ContextPropagationInterceptor : Interceptor +internal partial class ContextPropagationInterceptor : Interceptor { private readonly GrpcContextPropagationOptions _options; private readonly IHttpContextAccessor _httpContextAccessor; @@ -258,15 +258,10 @@ public async Task MoveNext(CancellationToken cancellationToken) } } - private static class Log + private static partial class Log { - private static readonly Action _propagateServerCallContextFailure = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "PropagateServerCallContextFailure"), "Unable to propagate server context values to the call. {ErrorMessage}"); - - public static void PropagateServerCallContextFailure(ILogger logger, string errorMessage) - { - _propagateServerCallContextFailure(logger, errorMessage, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "PropagateServerCallContextFailure", Message = "Unable to propagate server context values to the call. {ErrorMessage}")] + public static partial void PropagateServerCallContextFailure(ILogger logger, string errorMessage); } // Store static callbacks so delegates are allocated once diff --git a/src/Grpc.AspNetCore.Server.Reflection/GrpcReflectionServiceExtensions.cs b/src/Grpc.AspNetCore.Server.Reflection/GrpcReflectionServiceExtensions.cs index c8e3770f8..a236ab412 100644 --- a/src/Grpc.AspNetCore.Server.Reflection/GrpcReflectionServiceExtensions.cs +++ b/src/Grpc.AspNetCore.Server.Reflection/GrpcReflectionServiceExtensions.cs @@ -31,7 +31,7 @@ namespace Microsoft.Extensions.DependencyInjection; /// /// Extension methods for the gRPC reflection services. /// -public static class GrpcReflectionServiceExtensions +public static partial class GrpcReflectionServiceExtensions { /// /// Adds gRPC reflection services to the specified . @@ -150,14 +150,13 @@ public static IServiceCollection AddGrpcReflection(this IServiceCollection servi return baseType; } - private static class Log + private static partial class Log { - private static readonly Action _serviceDescriptorNotResolved = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "ServiceDescriptorNotResolved"), "Could not resolve service descriptor for '{ServiceType}'. The service metadata will not be exposed by the reflection service."); - + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "ServiceDescriptorNotResolved", Message = "Could not resolve service descriptor for '{ServiceType}'. The service metadata will not be exposed by the reflection service.")] + private static partial void ServiceDescriptorNotResolved(ILogger logger, string serviceType); public static void ServiceDescriptorNotResolved(ILogger logger, Type serviceType) { - _serviceDescriptorNotResolved(logger, serviceType.FullName ?? string.Empty, null); + ServiceDescriptorNotResolved(logger, serviceType.FullName ?? string.Empty); } } } diff --git a/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs b/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs index 884a6021d..73e991554 100644 --- a/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs +++ b/src/Grpc.AspNetCore.Server/Internal/GrpcServerLog.cs @@ -21,229 +21,89 @@ namespace Grpc.AspNetCore.Server.Internal; -internal static class GrpcServerLog +internal static partial class GrpcServerLog { - private static readonly Action _unableToDisableMaxRequestBodySize = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "UnableToDisableMaxRequestBodySizeLimit"), "Unable to disable the max request body size limit."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "UnableToDisableMaxRequestBodySizeLimit", Message = "Unable to disable the max request body size limit.")] + public static partial void UnableToDisableMaxRequestBodySize(ILogger logger); - private static readonly Action _unsupportedRequestContentType = - LoggerMessage.Define(LogLevel.Information, new EventId(2, "UnsupportedRequestContentType"), "Request content-type of '{ContentType}' is not supported."); + [LoggerMessage(Level = LogLevel.Information, EventId = 2, EventName = "UnsupportedRequestContentType", Message = "Request content-type of '{ContentType}' is not supported.")] + public static partial void UnsupportedRequestContentType(ILogger logger, string? contentType); - private static readonly Action _unsupportedRequestProtocol = - LoggerMessage.Define(LogLevel.Information, new EventId(3, "UnsupportedRequestProtocol"), "Request protocol of '{Protocol}' is not supported."); + [LoggerMessage(Level = LogLevel.Information, EventId = 3, EventName = "UnsupportedRequestProtocol", Message = "Request protocol of '{Protocol}' is not supported.")] + public static partial void UnsupportedRequestProtocol(ILogger logger, string? protocol); - private static readonly Action _deadlineExceeded = - LoggerMessage.Define(LogLevel.Debug, new EventId(4, "DeadlineExceeded"), "Request with timeout of {Timeout} has exceeded its deadline."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 4, EventName = "DeadlineExceeded", Message = "Request with timeout of {Timeout} has exceeded its deadline.")] + public static partial void DeadlineExceeded(ILogger logger, TimeSpan timeout); - private static readonly Action _invalidTimeoutIgnored = - LoggerMessage.Define(LogLevel.Debug, new EventId(5, "InvalidTimeoutIgnored"), "Invalid grpc-timeout header value '{Timeout}' has been ignored."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 5, EventName = "InvalidTimeoutIgnored", Message = "Invalid grpc-timeout header value '{Timeout}' has been ignored.")] + public static partial void InvalidTimeoutIgnored(ILogger logger, string timeout); - private static readonly Action _errorExecutingServiceMethod = - LoggerMessage.Define(LogLevel.Error, new EventId(6, "ErrorExecutingServiceMethod"), "Error when executing service method '{ServiceMethod}'."); + [LoggerMessage(Level = LogLevel.Error, EventId = 6, EventName = "ErrorExecutingServiceMethod", Message = "Error when executing service method '{ServiceMethod}'.")] + public static partial void ErrorExecutingServiceMethod(ILogger logger, string serviceMethod, Exception ex); - private static readonly Action _rpcConnectionError = - LoggerMessage.Define(LogLevel.Information, new EventId(7, "RpcConnectionError"), "Error status code '{StatusCode}' with detail '{Detail}' raised."); + [LoggerMessage(Level = LogLevel.Information, EventId = 7, EventName = "RpcConnectionError", Message = "Error status code '{StatusCode}' with detail '{Detail}' raised.")] + public static partial void RpcConnectionError(ILogger logger, StatusCode statusCode, string detail, Exception? debugException); - private static readonly Action _encodingNotInAcceptEncoding = - LoggerMessage.Define(LogLevel.Debug, new EventId(8, "EncodingNotInAcceptEncoding"), "Request grpc-encoding header value '{GrpcEncoding}' is not in grpc-accept-encoding."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 8, EventName = "EncodingNotInAcceptEncoding", Message = "Request grpc-encoding header value '{GrpcEncoding}' is not in grpc-accept-encoding.")] + public static partial void EncodingNotInAcceptEncoding(ILogger logger, string grpcEncoding); - private static readonly Action _deadlineCancellationError = - LoggerMessage.Define(LogLevel.Error, new EventId(9, "DeadlineCancellationError"), "Error occurred while trying to cancel the request due to deadline exceeded."); + [LoggerMessage(Level = LogLevel.Error, EventId = 9, EventName = "DeadlineCancellationError", Message = "Error occurred while trying to cancel the request due to deadline exceeded.")] + public static partial void DeadlineCancellationError(ILogger logger, Exception ex); - private static readonly Action _readingMessage = - LoggerMessage.Define(LogLevel.Debug, new EventId(10, "ReadingMessage"), "Reading message."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 10, EventName = "ReadingMessage", Message = "Reading message.")] + public static partial void ReadingMessage(ILogger logger); - private static readonly Action _noMessageReturned = - LoggerMessage.Define(LogLevel.Trace, new EventId(11, "NoMessageReturned"), "No message returned."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 11, EventName = "NoMessageReturned", Message = "No message returned.")] + public static partial void NoMessageReturned(ILogger logger); - private static readonly Action _deserializingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(12, "DeserializingMessage"), "Deserializing {MessageLength} byte message to '{MessageType}'."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 12, EventName = "DeserializingMessage", Message = "Deserializing {MessageLength} byte message to '{MessageType}'.")] + public static partial void DeserializingMessage(ILogger logger, int messageLength, Type messageType); - private static readonly Action _receivedMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(13, "ReceivedMessage"), "Received message."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 13, EventName = "ReceivedMessage", Message = "Received message.")] + public static partial void ReceivedMessage(ILogger logger); - private static readonly Action _errorReadingMessage = - LoggerMessage.Define(LogLevel.Information, new EventId(14, "ErrorReadingMessage"), "Error reading message."); + [LoggerMessage(Level = LogLevel.Information, EventId = 14, EventName = "ErrorReadingMessage", Message = "Error reading message.")] + public static partial void ErrorReadingMessage(ILogger logger, Exception ex); - private static readonly Action _sendingMessage = - LoggerMessage.Define(LogLevel.Debug, new EventId(15, "SendingMessage"), "Sending message."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 15, EventName = "SendingMessage", Message = "Sending message.")] + public static partial void SendingMessage(ILogger logger); - private static readonly Action _messageSent = - LoggerMessage.Define(LogLevel.Trace, new EventId(16, "MessageSent"), "Message sent."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 16, EventName = "MessageSent", Message = "Message sent.")] + public static partial void MessageSent(ILogger logger); - private static readonly Action _errorSendingMessage = - LoggerMessage.Define(LogLevel.Information, new EventId(17, "ErrorSendingMessage"), "Error sending message."); + [LoggerMessage(Level = LogLevel.Information, EventId = 17, EventName = "ErrorSendingMessage", Message = "Error sending message.")] + public static partial void ErrorSendingMessage(ILogger logger, Exception ex); - private static readonly Action _serializedMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(18, "SerializedMessage"), "Serialized '{MessageType}' to {MessageLength} byte message."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 18, EventName = "SerializedMessage", Message = "Serialized '{MessageType}' to {MessageLength} byte message.")] + public static partial void SerializedMessage(ILogger logger, Type messageType, int messageLength); - private static readonly Action _compressingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(19, "CompressingMessage"), "Compressing message with '{MessageEncoding}' encoding."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 19, EventName = "CompressingMessage", Message = "Compressing message with '{MessageEncoding}' encoding.")] + public static partial void CompressingMessage(ILogger logger, string messageEncoding); - private static readonly Action _decompressingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(20, "DecompressingMessage"), "Decompressing message with '{MessageEncoding}' encoding."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 20, EventName = "DecompressingMessage", Message = "Decompressing message with '{MessageEncoding}' encoding.")] + public static partial void DecompressingMessage(ILogger logger, string messageEncoding); - private static readonly Action _resettingResponse = - LoggerMessage.Define(LogLevel.Debug, new EventId(21, "ResettingResponse"), "Resetting response stream with error code {ErrorCode}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 21, EventName = "ResettingResponse", Message = "Resetting response stream with error code {ErrorCode}.")] + public static partial void ResettingResponse(ILogger logger, int errorCode); - private static readonly Action _abortingResponse = - LoggerMessage.Define(LogLevel.Debug, new EventId(22, "AbortingResponse"), "IHttpResetFeature is not available so unable to cleanly reset response stream. Aborting response stream."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 22, EventName = "AbortingResponse", Message = "IHttpResetFeature is not available so unable to cleanly reset response stream. Aborting response stream.")] + public static partial void AbortingResponse(ILogger logger); - private static readonly Action _unhandledCorsPreflightRequest = - LoggerMessage.Define(LogLevel.Information, new EventId(23, "UnhandledCorsPreflightRequest"), "Unhandled CORS preflight request received. CORS may not be configured correctly in the application."); + [LoggerMessage(Level = LogLevel.Information, EventId = 23, EventName = "UnhandledCorsPreflightRequest", Message = "Unhandled CORS preflight request received. CORS may not be configured correctly in the application.")] + public static partial void UnhandledCorsPreflightRequest(ILogger logger); - private static readonly Action _deadlineTimeoutTooLong = - LoggerMessage.Define(LogLevel.Debug, new EventId(24, "DeadlineTimeoutTooLong"), "Deadline timeout {Timeout} is above maximum allowed timeout of 99999999 seconds. Maximum timeout will be used."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 24, EventName = "DeadlineTimeoutTooLong", Message = "Deadline timeout {Timeout} is above maximum allowed timeout of 99999999 seconds. Maximum timeout will be used.")] + public static partial void DeadlineTimeoutTooLong(ILogger logger, TimeSpan timeout); - private static readonly Action _deadlineTimerRescheduled = - LoggerMessage.Define(LogLevel.Trace, new EventId(25, "DeadlineTimerRescheduled"), "Deadline timer triggered but {Remaining} remaining before deadline exceeded. Deadline timer rescheduled."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 25, EventName = "DeadlineTimerRescheduled", Message = "Deadline timer triggered but {Remaining} remaining before deadline exceeded. Deadline timer rescheduled.")] + public static partial void DeadlineTimerRescheduled(ILogger logger, TimeSpan remaining); - private static readonly Action _deadlineStarted = - LoggerMessage.Define(LogLevel.Trace, new EventId(26, "DeadlineStarted"), "Request deadline timeout of {Timeout} started."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 26, EventName = "DeadlineStarted", Message = "Request deadline timeout of {Timeout} started.")] + public static partial void DeadlineStarted(ILogger logger, TimeSpan timeout); - private static readonly Action _deadlineStopped = - LoggerMessage.Define(LogLevel.Trace, new EventId(27, "DeadlineStopped"), "Request deadline stopped."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 27, EventName = "DeadlineStopped", Message = "Request deadline stopped.")] + internal static partial void DeadlineStopped(ILogger logger); - private static readonly Action _serviceMethodCanceled = - LoggerMessage.Define(LogLevel.Information, new EventId(28, "ServiceMethodCanceled"), "Service method '{ServiceMethod}' canceled."); - - internal static void DeadlineStopped(ILogger logger) - { - _deadlineStopped(logger, null); - } - - public static void DeadlineStarted(ILogger logger, TimeSpan timeout) - { - _deadlineStarted(logger, timeout, null); - } - - public static void DeadlineExceeded(ILogger logger, TimeSpan timeout) - { - _deadlineExceeded(logger, timeout, null); - } - - public static void InvalidTimeoutIgnored(ILogger logger, string timeout) - { - _invalidTimeoutIgnored(logger, timeout, null); - } - - public static void ErrorExecutingServiceMethod(ILogger logger, string serviceMethod, Exception ex) - { - _errorExecutingServiceMethod(logger, serviceMethod, ex); - } - - public static void RpcConnectionError(ILogger logger, StatusCode statusCode, string detail, Exception? debugException) - { - _rpcConnectionError(logger, statusCode, detail, debugException); - } - - public static void EncodingNotInAcceptEncoding(ILogger logger, string grpcEncoding) - { - _encodingNotInAcceptEncoding(logger, grpcEncoding, null); - } - - public static void DeadlineCancellationError(ILogger logger, Exception ex) - { - _deadlineCancellationError(logger, ex); - } - - public static void UnableToDisableMaxRequestBodySize(ILogger logger) - { - _unableToDisableMaxRequestBodySize(logger, null); - } - - public static void UnsupportedRequestContentType(ILogger logger, string? contentType) - { - _unsupportedRequestContentType(logger, contentType, null); - } - - public static void UnsupportedRequestProtocol(ILogger logger, string? protocol) - { - _unsupportedRequestProtocol(logger, protocol, null); - } - - public static void ReadingMessage(ILogger logger) - { - _readingMessage(logger, null); - } - - public static void NoMessageReturned(ILogger logger) - { - _noMessageReturned(logger, null); - } - - public static void DeserializingMessage(ILogger logger, int messageLength, Type messageType) - { - _deserializingMessage(logger, messageLength, messageType, null); - } - - public static void ReceivedMessage(ILogger logger) - { - _receivedMessage(logger, null); - } - - public static void ErrorReadingMessage(ILogger logger, Exception ex) - { - _errorReadingMessage(logger, ex); - } - - public static void SendingMessage(ILogger logger) - { - _sendingMessage(logger, null); - } - - public static void MessageSent(ILogger logger) - { - _messageSent(logger, null); - } - - public static void ErrorSendingMessage(ILogger logger, Exception ex) - { - _errorSendingMessage(logger, ex); - } - - public static void SerializedMessage(ILogger logger, Type messageType, int messageLength) - { - _serializedMessage(logger, messageType, messageLength, null); - } - - public static void CompressingMessage(ILogger logger, string messageEncoding) - { - _compressingMessage(logger, messageEncoding, null); - } - - public static void DecompressingMessage(ILogger logger, string messageEncoding) - { - _decompressingMessage(logger, messageEncoding, null); - } - - public static void ResettingResponse(ILogger logger, int errorCode) - { - _resettingResponse(logger, errorCode, null); - } - - public static void AbortingResponse(ILogger logger) - { - _abortingResponse(logger, null); - } - - public static void UnhandledCorsPreflightRequest(ILogger logger) - { - _unhandledCorsPreflightRequest(logger, null); - } - - public static void DeadlineTimeoutTooLong(ILogger logger, TimeSpan timeout) - { - _deadlineTimeoutTooLong(logger, timeout, null); - } - - public static void DeadlineTimerRescheduled(ILogger logger, TimeSpan remaining) - { - _deadlineTimerRescheduled(logger, remaining, null); - } - - public static void ServiceMethodCanceled(ILogger logger, string serviceMethod, Exception ex) - { - _serviceMethodCanceled(logger, serviceMethod, ex); - } + [LoggerMessage(Level = LogLevel.Information, EventId = 28, EventName = "ServiceMethodCanceled", Message = "Service method '{ServiceMethod}' canceled.")] + public static partial void ServiceMethodCanceled(ILogger logger, string serviceMethod, Exception ex); } diff --git a/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs b/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs index 9d41c3520..95d545942 100644 --- a/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs +++ b/src/Grpc.AspNetCore.Server/Internal/ServerCallHandlerFactory.cs @@ -154,21 +154,11 @@ public RequestDelegate CreateUnimplementedService() } } -internal static class ServerCallHandlerFactoryLog +internal static partial class ServerCallHandlerFactoryLog { - private static readonly Action _serviceUnimplemented = - LoggerMessage.Define(LogLevel.Information, new EventId(1, "ServiceUnimplemented"), "Service '{ServiceName}' is unimplemented."); + [LoggerMessage(Level = LogLevel.Information, EventId = 1, EventName = "ServiceUnimplemented", Message = "Service '{ServiceName}' is unimplemented.")] + public static partial void ServiceUnimplemented(ILogger logger, string serviceName); - private static readonly Action _methodUnimplemented = - LoggerMessage.Define(LogLevel.Information, new EventId(2, "MethodUnimplemented"), "Method '{MethodName}' is unimplemented."); - - public static void ServiceUnimplemented(ILogger logger, string serviceName) - { - _serviceUnimplemented(logger, serviceName, null); - } - - public static void MethodUnimplemented(ILogger logger, string methodName) - { - _methodUnimplemented(logger, methodName, null); - } + [LoggerMessage(Level = LogLevel.Information, EventId = 2, EventName = "MethodUnimplemented", Message = "Method '{MethodName}' is unimplemented.")] + public static partial void MethodUnimplemented(ILogger logger, string methodName); } diff --git a/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs b/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs index db6fce070..101ee27e6 100644 --- a/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs +++ b/src/Grpc.AspNetCore.Server/Model/Internal/BinderServiceModelProvider.cs @@ -61,13 +61,8 @@ public void OnServiceMethodDiscovery(ServiceMethodProviderContext cont } } -internal static class BinderServiceMethodProviderLog +internal static partial class BinderServiceMethodProviderLog { - private static readonly Action _bindMethodNotFound = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "BindMethodNotFound"), "Could not find bind method for {ServiceType}."); - - public static void BindMethodNotFound(ILogger logger, Type serviceType) - { - _bindMethodNotFound(logger, serviceType, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "BindMethodNotFound", Message = "Could not find bind method for {ServiceType}.")] + public static partial void BindMethodNotFound(ILogger logger, Type serviceType); } diff --git a/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs b/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs index 83d8875ae..dc3613ffa 100644 --- a/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs +++ b/src/Grpc.AspNetCore.Server/Model/Internal/ServiceRouteBuilder.cs @@ -156,16 +156,10 @@ private static IEndpointConventionBuilder CreateUnimplementedEndpoint(IEndpointR } } -internal static class ServiceRouteBuilderLog +internal static partial class ServiceRouteBuilderLog { - private static readonly Action _addedServiceMethod = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "AddedServiceMethod"), "Added gRPC method '{MethodName}' to service '{ServiceName}'. Method type: {MethodType}, HTTP method: {HttpMethod}, route pattern: '{RoutePattern}'."); - - private static readonly Action _discoveringServiceMethods = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "DiscoveringServiceMethods"), "Discovering gRPC methods for {ServiceType}."); - - private static readonly Action _noServiceMethodsDiscovered = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "NoServiceMethodsDiscovered"), "No gRPC methods discovered for {ServiceType}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "AddedServiceMethod", Message = "Added gRPC method '{MethodName}' to service '{ServiceName}'. Method type: {MethodType}, HTTP method: {HttpMethod}, route pattern: '{RoutePattern}'.")] + private static partial void AddedServiceMethod(ILogger logger, string methodName, string serviceName, MethodType methodType, string HttpMethod, string routePattern); public static void AddedServiceMethod(ILogger logger, string methodName, string serviceName, MethodType methodType, IReadOnlyList httpMethods, string routePattern) { @@ -174,17 +168,13 @@ public static void AddedServiceMethod(ILogger logger, string methodName, string // There should be one HTTP method here, but concat in case someone has overriden metadata. var allHttpMethods = string.Join(',', httpMethods); - _addedServiceMethod(logger, methodName, serviceName, methodType, allHttpMethods, routePattern, null); + AddedServiceMethod(logger, methodName, serviceName, methodType, allHttpMethods, routePattern); } } - public static void DiscoveringServiceMethods(ILogger logger, Type serviceType) - { - _discoveringServiceMethods(logger, serviceType, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "DiscoveringServiceMethods", Message = "Discovering gRPC methods for {ServiceType}.")] + public static partial void DiscoveringServiceMethods(ILogger logger, Type serviceType); - public static void NoServiceMethodsDiscovered(ILogger logger, Type serviceType) - { - _noServiceMethodsDiscovered(logger, serviceType, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "NoServiceMethodsDiscovered", Message = "No gRPC methods discovered for {ServiceType}.")] + public static partial void NoServiceMethodsDiscovered(ILogger logger, Type serviceType); } diff --git a/src/Grpc.AspNetCore.Web/Internal/GrpcWebMiddleware.cs b/src/Grpc.AspNetCore.Web/Internal/GrpcWebMiddleware.cs index ece1298f3..a10ba975f 100644 --- a/src/Grpc.AspNetCore.Web/Internal/GrpcWebMiddleware.cs +++ b/src/Grpc.AspNetCore.Web/Internal/GrpcWebMiddleware.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -24,7 +24,7 @@ namespace Grpc.AspNetCore.Web.Internal; -internal sealed class GrpcWebMiddleware +internal sealed partial class GrpcWebMiddleware { private readonly GrpcWebOptions _options; private readonly ILogger _logger; @@ -158,30 +158,15 @@ private static bool TryGetWebMode(string? contentType, out ServerGrpcWebMode mod return false; } - private static class Log + private static partial class Log { - private static readonly Action _detectedGrpcWebRequest = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "DetectedGrpcWebRequest"), "Detected gRPC-Web request from content-type '{ContentType}'."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "DetectedGrpcWebRequest", Message = "Detected gRPC-Web request from content-type '{ContentType}'.")] + public static partial void DetectedGrpcWebRequest(ILogger logger, string contentType); - private static readonly Action _grpcWebRequestNotProcessed = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "GrpcWebRequestNotProcessed"), $"gRPC-Web request not processed. gRPC-Web must be enabled by placing the [EnableGrpcWeb] attribute on a service or method, or enable for all services in the app with {nameof(GrpcWebOptions)}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "GrpcWebRequestNotProcessed", Message = $"gRPC-Web request not processed. gRPC-Web must be enabled by placing the [EnableGrpcWeb] attribute on a service or method, or enable for all services in the app with {nameof(GrpcWebOptions)}.")] + public static partial void GrpcWebRequestNotProcessed(ILogger logger); - private static readonly Action _sendingGrpcWebResponse = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "SendingGrpcWebResponse"), "Sending gRPC-Web response with content-type '{ContentType}'."); - - public static void DetectedGrpcWebRequest(ILogger logger, string contentType) - { - _detectedGrpcWebRequest(logger, contentType, null); - } - - public static void GrpcWebRequestNotProcessed(ILogger logger) - { - _grpcWebRequestNotProcessed(logger, null); - } - - public static void SendingGrpcWebResponse(ILogger logger, string contentType) - { - _sendingGrpcWebResponse(logger, contentType, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "SendingGrpcWebResponse", Message = "Sending gRPC-Web response with content-type '{ContentType}'.")] + public static partial void SendingGrpcWebResponse(ILogger logger, string contentType); } } diff --git a/src/Grpc.Net.Client/Balancer/DnsResolver.cs b/src/Grpc.Net.Client/Balancer/DnsResolver.cs index 2ae026594..d8cb1b39e 100644 --- a/src/Grpc.Net.Client/Balancer/DnsResolver.cs +++ b/src/Grpc.Net.Client/Balancer/DnsResolver.cs @@ -145,50 +145,30 @@ private void OnTimerCallback(object? state) } } -internal static class DnsResolverLog +internal static partial class DnsResolverLog { - private static readonly Action _startingRateLimitDelay = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "StartingRateLimitDelay"), "Starting rate limit delay of {DelayDuration}. DNS resolution rate limit is once every {RateLimitDuration}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "StartingRateLimitDelay", Message = "Starting rate limit delay of {DelayDuration}. DNS resolution rate limit is once every {RateLimitDuration}.")] + public static partial void StartingRateLimitDelay(ILogger logger, TimeSpan delayDuration, TimeSpan rateLimitDuration); - private static readonly Action _startingDnsQuery = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "StartingDnsQuery"), "Starting DNS query to get hosts from '{DnsAddress}'."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "StartingDnsQuery", Message = "Starting DNS query to get hosts from '{DnsAddress}'.")] + public static partial void StartingDnsQuery(ILogger logger, string dnsAddress); - private static readonly Action _receivedDnsResults = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "ReceivedDnsResults"), "Received {ResultCount} DNS results from '{DnsAddress}'. Results: {DnsResults}"); - - private static readonly Action _errorQueryingDns = - LoggerMessage.Define(LogLevel.Error, new EventId(4, "ErrorQueryingDns"), "Error querying DNS hosts for '{DnsAddress}'."); - - private static readonly Action _errorFromRefreshInterval = - LoggerMessage.Define(LogLevel.Error, new EventId(5, "ErrorFromRefreshIntervalTimer"), "Error from refresh interval timer."); - - public static void StartingRateLimitDelay(ILogger logger, TimeSpan delayDuration, TimeSpan rateLimitDuration) - { - _startingRateLimitDelay(logger, delayDuration, rateLimitDuration, null); - } - - public static void StartingDnsQuery(ILogger logger, string dnsAddress) - { - _startingDnsQuery(logger, dnsAddress, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "ReceivedDnsResults", Message = "Received {ResultCount} DNS results from '{DnsAddress}'. Results: {DnsResults}")] + private static partial void ReceivedDnsResults(ILogger logger, int resultCount, string dnsAddress, string dnsResults); public static void ReceivedDnsResults(ILogger logger, int resultCount, string dnsAddress, IList dnsResults) { if (logger.IsEnabled(LogLevel.Debug)) { - _receivedDnsResults(logger, resultCount, dnsAddress, string.Join(", ", dnsResults), null); + ReceivedDnsResults(logger, resultCount, dnsAddress, string.Join(", ", dnsResults)); } } - public static void ErrorQueryingDns(ILogger logger, string dnsAddress, Exception ex) - { - _errorQueryingDns(logger, dnsAddress, ex); - } + [LoggerMessage(Level = LogLevel.Error, EventId = 4, EventName = "ErrorQueryingDns", Message = "Error querying DNS hosts for '{DnsAddress}'.")] + public static partial void ErrorQueryingDns(ILogger logger, string dnsAddress, Exception ex); - public static void ErrorFromRefreshInterval(ILogger logger, Exception ex) - { - _errorFromRefreshInterval(logger, ex); - } + [LoggerMessage(Level = LogLevel.Error, EventId = 5, EventName = "ErrorFromRefreshIntervalTimer", Message = "Error from refresh interval timer.")] + public static partial void ErrorFromRefreshInterval(ILogger logger, Exception ex); } /// diff --git a/src/Grpc.Net.Client/Balancer/Internal/BalancerHttpHandler.cs b/src/Grpc.Net.Client/Balancer/Internal/BalancerHttpHandler.cs index 33bb1d8b5..37bc3c7e9 100644 --- a/src/Grpc.Net.Client/Balancer/Internal/BalancerHttpHandler.cs +++ b/src/Grpc.Net.Client/Balancer/Internal/BalancerHttpHandler.cs @@ -29,7 +29,7 @@ namespace Grpc.Net.Client.Balancer.Internal; -internal class BalancerHttpHandler : DelegatingHandler +internal partial class BalancerHttpHandler : DelegatingHandler { private static readonly object SetupLock = new object(); @@ -171,24 +171,20 @@ protected override async Task SendAsync( } } - internal static class Log + internal static partial class Log { - private static readonly Action _sendingRequest = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "SendingRequest"), "Sending request {RequestUri}."); - private static readonly Action _startingConnectCallback = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "StartingConnectCallback"), "Starting connect callback for {Endpoint}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "SendingRequest", Message = "Sending request {RequestUri}.")] + public static partial void SendingRequest(ILogger logger, Uri requestUri); - public static void SendingRequest(ILogger logger, Uri requestUri) - { - _sendingRequest(logger, requestUri, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "StartingConnectCallback", Message = "Starting connect callback for {Endpoint}.")] + private static partial void StartingConnectCallback(ILogger logger, string endpoint); public static void StartingConnectCallback(ILogger logger, DnsEndPoint endpoint) { if (logger.IsEnabled(LogLevel.Trace)) { - _startingConnectCallback(logger, $"{endpoint.Host}:{endpoint.Port}", null); + StartingConnectCallback(logger, $"{endpoint.Host}:{endpoint.Port}"); } } } diff --git a/src/Grpc.Net.Client/Balancer/Internal/ConnectionManager.cs b/src/Grpc.Net.Client/Balancer/Internal/ConnectionManager.cs index b64a4557c..3512d9b45 100644 --- a/src/Grpc.Net.Client/Balancer/Internal/ConnectionManager.cs +++ b/src/Grpc.Net.Client/Balancer/Internal/ConnectionManager.cs @@ -469,114 +469,54 @@ public void Dispose() } } -internal static class ConnectionManagerLog +internal static partial class ConnectionManagerLog { - private static readonly Action _resolverUnsupportedLoadBalancingConfig = - LoggerMessage.Define(LogLevel.Warning, new EventId(1, "ResolverUnsupportedLoadBalancingConfig"), "Service config returned by the resolver contains unsupported load balancer policies: {LoadBalancingConfigs}. Load balancer unchanged."); - - private static readonly Action _resolverServiceConfigNotUsed = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "ResolverServiceConfigNotUsed"), "Service config returned by the resolver not used."); - - private static readonly Action _channelStateUpdated = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "ChannelStateUpdated"), "Channel state updated to {State}."); - - private static readonly Action _channelPickerUpdated = - LoggerMessage.Define(LogLevel.Debug, new EventId(4, "ChannelPickerUpdated"), "Channel picker updated."); - - private static readonly Action _pickStarted = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "PickStarted"), "Pick started."); - - private static readonly Action _pickResultSuccessful = - LoggerMessage.Define(LogLevel.Debug, new EventId(6, "PickResultSuccessful"), "Successfully picked subchannel id '{SubchannelId}' with address {CurrentAddress}. Transport status: {TransportStatus}"); - - private static readonly Action _pickResultSubchannelNoCurrentAddress = - LoggerMessage.Define(LogLevel.Debug, new EventId(7, "PickResultSubchannelNoCurrentAddress"), "Picked subchannel id '{SubchannelId}' doesn't have a current address."); - - private static readonly Action _pickResultQueued = - LoggerMessage.Define(LogLevel.Debug, new EventId(8, "PickResultQueued"), "Picked queued."); - - private static readonly Action _pickResultFailure = - LoggerMessage.Define(LogLevel.Debug, new EventId(9, "PickResultFailure"), "Picked failure with status: {Status}"); - - private static readonly Action _pickResultFailureWithWaitForReady = - LoggerMessage.Define(LogLevel.Debug, new EventId(10, "PickResultFailureWithWaitForReady"), "Picked failure with status: {Status}. Retrying because wait for ready is enabled."); - - private static readonly Action _pickWaiting = - LoggerMessage.Define(LogLevel.Trace, new EventId(11, "PickWaiting"), "Waiting for a new picker."); - - private static readonly Action _resolverServiceConfigFallback = - LoggerMessage.Define(LogLevel.Debug, new EventId(12, "ResolverServiceConfigFallback"), "Falling back to previously loaded service config. Resolver failure when retreiving or parsing service config with status: {Status}"); - - private static readonly Action _pickResultSubchannelNotReady = - LoggerMessage.Define(LogLevel.Debug, new EventId(13, "PickResultSubchannelNotReady"), "Picked subchannel id '{SubchannelId}' with address {CurrentAddress} doesn't have a ready state. Subchannel state: {State}"); + [LoggerMessage(Level = LogLevel.Warning, EventId = 1, EventName = "ResolverUnsupportedLoadBalancingConfig", Message = "Service config returned by the resolver contains unsupported load balancer policies: {LoadBalancingConfigs}. Load balancer unchanged.")] + private static partial void ResolverUnsupportedLoadBalancingConfig(ILogger logger, string loadBalancingConfigs); public static void ResolverUnsupportedLoadBalancingConfig(ILogger logger, IList loadBalancingConfigs) { if (logger.IsEnabled(LogLevel.Warning)) { var loadBalancingConfigText = string.Join(", ", loadBalancingConfigs.Select(c => $"'{c.PolicyName}'")); - _resolverUnsupportedLoadBalancingConfig(logger, loadBalancingConfigText, null); + ResolverUnsupportedLoadBalancingConfig(logger, loadBalancingConfigText); } } - public static void ResolverServiceConfigNotUsed(ILogger logger) - { - _resolverServiceConfigNotUsed(logger, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "ResolverServiceConfigNotUsed", Message = "Service config returned by the resolver not used.")] + public static partial void ResolverServiceConfigNotUsed(ILogger logger); - public static void ChannelStateUpdated(ILogger logger, ConnectivityState connectivityState) - { - _channelStateUpdated(logger, connectivityState, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "ChannelStateUpdated", Message = "Channel state updated to {State}.")] + public static partial void ChannelStateUpdated(ILogger logger, ConnectivityState state); - public static void ChannelPickerUpdated(ILogger logger) - { - _channelPickerUpdated(logger, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 4, EventName = "ChannelPickerUpdated", Message = "Channel picker updated.")] + public static partial void ChannelPickerUpdated(ILogger logger); - public static void PickStarted(ILogger logger) - { - _pickStarted(logger, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 5, EventName = "PickStarted", Message = "Pick started.")] + public static partial void PickStarted(ILogger logger); - public static void PickResultSuccessful(ILogger logger, string subchannelId, BalancerAddress currentAddress, TransportStatus transportStatus) - { - _pickResultSuccessful(logger, subchannelId, currentAddress, transportStatus, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 6, EventName = "PickResultSuccessful", Message = "Successfully picked subchannel id '{SubchannelId}' with address {CurrentAddress}. Transport status: {TransportStatus}")] + public static partial void PickResultSuccessful(ILogger logger, string subchannelId, BalancerAddress currentAddress, TransportStatus transportStatus); - public static void PickResultSubchannelNoCurrentAddress(ILogger logger, string subchannelId) - { - _pickResultSubchannelNoCurrentAddress(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 7, EventName = "PickResultSubchannelNoCurrentAddress", Message = "Picked subchannel id '{SubchannelId}' doesn't have a current address.")] + public static partial void PickResultSubchannelNoCurrentAddress(ILogger logger, string subchannelId); - public static void PickResultQueued(ILogger logger) - { - _pickResultQueued(logger, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 8, EventName = "PickResultQueued", Message = "Picked queued.")] + public static partial void PickResultQueued(ILogger logger); - public static void PickResultFailure(ILogger logger, Status status) - { - _pickResultFailure(logger, status, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 9, EventName = "PickResultFailure", Message = "Picked failure with status: {Status}")] + public static partial void PickResultFailure(ILogger logger, Status status); - public static void PickResultFailureWithWaitForReady(ILogger logger, Status status) - { - _pickResultFailureWithWaitForReady(logger, status, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 10, EventName = "PickResultFailureWithWaitForReady", Message = "Picked failure with status: {Status}. Retrying because wait for ready is enabled.")] + public static partial void PickResultFailureWithWaitForReady(ILogger logger, Status status); - public static void PickWaiting(ILogger logger) - { - _pickWaiting(logger, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 11, EventName = "PickWaiting", Message = "Waiting for a new picker.")] + public static partial void PickWaiting(ILogger logger); - public static void ResolverServiceConfigFallback(ILogger logger, Status status) - { - _resolverServiceConfigFallback(logger, status, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 12, EventName = "ResolverServiceConfigFallback", Message = "Falling back to previously loaded service config. Resolver failure when retreiving or parsing service config with status: {Status}")] + public static partial void ResolverServiceConfigFallback(ILogger logger, Status status); - public static void PickResultSubchannelNotReady(ILogger logger, string subchannelId, BalancerAddress currentAddress, ConnectivityState state) - { - _pickResultSubchannelNotReady(logger, subchannelId, currentAddress, state, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 13, EventName = "PickResultSubchannelNotReady", Message = "Picked subchannel id '{SubchannelId}' with address {CurrentAddress} doesn't have a ready state. Subchannel state: {State}")] + public static partial void PickResultSubchannelNotReady(ILogger logger, string subchannelId, BalancerAddress currentAddress, ConnectivityState state); } #endif diff --git a/src/Grpc.Net.Client/Balancer/Internal/SocketConnectivitySubchannelTransport.cs b/src/Grpc.Net.Client/Balancer/Internal/SocketConnectivitySubchannelTransport.cs index b54666d88..f1f3ffab3 100644 --- a/src/Grpc.Net.Client/Balancer/Internal/SocketConnectivitySubchannelTransport.cs +++ b/src/Grpc.Net.Client/Balancer/Internal/SocketConnectivitySubchannelTransport.cs @@ -544,142 +544,57 @@ public void Dispose() } } -internal static class SocketConnectivitySubchannelTransportLog +internal static partial class SocketConnectivitySubchannelTransportLog { - private static readonly Action _connectingSocket = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "ConnectingSocket"), "Subchannel id '{SubchannelId}' connecting socket to {EndPoint}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "ConnectingSocket", Message = "Subchannel id '{SubchannelId}' connecting socket to {EndPoint}.")] + public static partial void ConnectingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _connectedSocket = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "ConnectedSocket"), "Subchannel id '{SubchannelId}' connected to socket {EndPoint}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "ConnectedSocket", Message = "Subchannel id '{SubchannelId}' connected to socket {EndPoint}.")] + public static partial void ConnectedSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _errorConnectingSocket = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "ErrorConnectingSocket"), "Subchannel id '{SubchannelId}' error connecting to socket {EndPoint}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "ErrorConnectingSocket", Message = "Subchannel id '{SubchannelId}' error connecting to socket {EndPoint}.")] + public static partial void ErrorConnectingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex); - private static readonly Action _checkingSocket = - LoggerMessage.Define(LogLevel.Trace, new EventId(4, "CheckingSocket"), "Subchannel id '{SubchannelId}' checking socket {EndPoint}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 4, EventName = "CheckingSocket", Message = "Subchannel id '{SubchannelId}' checking socket {EndPoint}.")] + public static partial void CheckingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _errorCheckingSocket = - LoggerMessage.Define(LogLevel.Debug, new EventId(5, "ErrorCheckingSocket"), "Subchannel id '{SubchannelId}' error checking socket {EndPoint}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 5, EventName = "ErrorCheckingSocket", Message = "Subchannel id '{SubchannelId}' error checking socket {EndPoint}.")] + public static partial void ErrorCheckingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex); - private static readonly Action _errorSocketTimer = - LoggerMessage.Define(LogLevel.Error, new EventId(6, "ErrorSocketTimer"), "Subchannel id '{SubchannelId}' unexpected error in check socket timer."); + [LoggerMessage(Level = LogLevel.Error, EventId = 6, EventName = "ErrorSocketTimer", Message = "Subchannel id '{SubchannelId}' unexpected error in check socket timer.")] + public static partial void ErrorSocketTimer(ILogger logger, string subchannelId, Exception ex); - private static readonly Action _creatingStream = - LoggerMessage.Define(LogLevel.Trace, new EventId(7, "CreatingStream"), "Subchannel id '{SubchannelId}' creating stream for {EndPoint}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 7, EventName = "CreatingStream", Message = "Subchannel id '{SubchannelId}' creating stream for {EndPoint}.")] + public static partial void CreatingStream(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _disposingStream = - LoggerMessage.Define(LogLevel.Trace, new EventId(8, "DisposingStream"), "Subchannel id '{SubchannelId}' disposing stream for {EndPoint}. Transport has {ActiveStreams} active streams."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 8, EventName = "DisposingStream", Message = "Subchannel id '{SubchannelId}' disposing stream for {EndPoint}. Transport has {ActiveStreams} active streams.")] + public static partial void DisposingStream(ILogger logger, string subchannelId, DnsEndPoint endPoint, int activeStreams); - private static readonly Action _disposingTransport = - LoggerMessage.Define(LogLevel.Trace, new EventId(9, "DisposingTransport"), "Subchannel id '{SubchannelId}' disposing transport."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 9, EventName = "DisposingTransport", Message = "Subchannel id '{SubchannelId}' disposing transport.")] + public static partial void DisposingTransport(ILogger logger, string subchannelId); - private static readonly Action _errorOnDisposingStream = - LoggerMessage.Define(LogLevel.Error, new EventId(10, "ErrorOnDisposingStream"), "Subchannel id '{SubchannelId}' unexpected error when reacting to transport stream dispose."); + [LoggerMessage(Level = LogLevel.Error, EventId = 10, EventName = "ErrorOnDisposingStream", Message = "Subchannel id '{SubchannelId}' unexpected error when reacting to transport stream dispose.")] + public static partial void ErrorOnDisposingStream(ILogger logger, string subchannelId, Exception ex); - private static readonly Action _connectingOnCreateStream = - LoggerMessage.Define(LogLevel.Trace, new EventId(11, "ConnectingOnCreateStream"), "Subchannel id '{SubchannelId}' doesn't have a connected socket available. Connecting new stream socket for {EndPoint}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 11, EventName = "ConnectingOnCreateStream", Message = "Subchannel id '{SubchannelId}' doesn't have a connected socket available. Connecting new stream socket for {EndPoint}.")] + public static partial void ConnectingOnCreateStream(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _streamCreated = - LoggerMessage.Define(LogLevel.Trace, new EventId(12, "StreamCreated"), "Subchannel id '{SubchannelId}' created stream for {EndPoint} with {BufferedBytes} buffered bytes. Transport has {ActiveStreams} active streams."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 12, EventName = "StreamCreated", Message = "Subchannel id '{SubchannelId}' created stream for {EndPoint} with {BufferedBytes} buffered bytes. Transport has {ActiveStreams} active streams.")] + public static partial void StreamCreated(ILogger logger, string subchannelId, DnsEndPoint endPoint, int bufferedBytes, int activeStreams); - private static readonly Action _errorPollingSocket = - LoggerMessage.Define(LogLevel.Debug, new EventId(13, "ErrorPollingSocket"), "Subchannel id '{SubchannelId}' error checking socket {EndPoint}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 13, EventName = "ErrorPollingSocket", Message = "Subchannel id '{SubchannelId}' error checking socket {EndPoint}.")] + public static partial void ErrorPollingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex); - private static readonly Action _socketPollBadState = - LoggerMessage.Define(LogLevel.Debug, new EventId(14, "SocketPollBadState"), "Subchannel id '{SubchannelId}' socket {EndPoint} is in a bad state and can't be used."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 14, EventName = "SocketPollBadState", Message = "Subchannel id '{SubchannelId}' socket {EndPoint} is in a bad state and can't be used.")] + public static partial void SocketPollBadState(ILogger logger, string subchannelId, DnsEndPoint endPoint); - private static readonly Action _socketReceivingAvailable = - LoggerMessage.Define(LogLevel.Trace, new EventId(15, "SocketReceivingAvailable"), "Subchannel id '{SubchannelId}' socket {EndPoint} is receiving {ReadBytesAvailableCount} available bytes."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 15, EventName = "SocketReceivingAvailable", Message = "Subchannel id '{SubchannelId}' socket {EndPoint} is receiving {ReadBytesAvailableCount} available bytes.")] + public static partial void SocketReceivingAvailable(ILogger logger, string subchannelId, DnsEndPoint endPoint, int readBytesAvailableCount); - private static readonly Action _closingUnusableSocket = - LoggerMessage.Define(LogLevel.Debug, new EventId(16, "ClosingUnusableSocket"), "Subchannel id '{SubchannelId}' socket {EndPoint} is being closed because it can't be used. Socket lifetime of {SocketLifetime}. The socket either can't receive data or it has received unexpected data."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 16, EventName = "ClosingUnusableSocket", Message = "Subchannel id '{SubchannelId}' socket {EndPoint} is being closed because it can't be used. Socket lifetime of {SocketLifetime}. The socket either can't receive data or it has received unexpected data.")] + public static partial void ClosingUnusableSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, TimeSpan socketLifetime); - private static readonly Action _closingSocketFromIdleTimeoutOnCreateStream = - LoggerMessage.Define(LogLevel.Debug, new EventId(16, "ClosingSocketFromIdleTimeoutOnCreateStream"), "Subchannel id '{SubchannelId}' socket {EndPoint} is being closed because it exceeds the idle timeout of {SocketIdleTimeout}."); - - public static void ConnectingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _connectingSocket(logger, subchannelId, endPoint, null); - } - - public static void ConnectedSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _connectedSocket(logger, subchannelId, endPoint, null); - } - - public static void ErrorConnectingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex) - { - _errorConnectingSocket(logger, subchannelId, endPoint, ex); - } - - public static void CheckingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _checkingSocket(logger, subchannelId, endPoint, null); - } - - public static void ErrorCheckingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex) - { - _errorCheckingSocket(logger, subchannelId, endPoint, ex); - } - - public static void ErrorSocketTimer(ILogger logger, string subchannelId, Exception ex) - { - _errorSocketTimer(logger, subchannelId, ex); - } - - public static void CreatingStream(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _creatingStream(logger, subchannelId, endPoint, null); - } - - public static void DisposingStream(ILogger logger, string subchannelId, DnsEndPoint endPoint, int activeStreams) - { - _disposingStream(logger, subchannelId, endPoint, activeStreams, null); - } - - public static void DisposingTransport(ILogger logger, string subchannelId) - { - _disposingTransport(logger, subchannelId, null); - } - - public static void ErrorOnDisposingStream(ILogger logger, string subchannelId, Exception ex) - { - _errorOnDisposingStream(logger, subchannelId, ex); - } - - public static void ConnectingOnCreateStream(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _connectingOnCreateStream(logger, subchannelId, endPoint, null); - } - - public static void StreamCreated(ILogger logger, string subchannelId, DnsEndPoint endPoint, int bufferedBytes, int activeStreams) - { - _streamCreated(logger, subchannelId, endPoint, bufferedBytes, activeStreams, null); - } - - public static void ErrorPollingSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, Exception ex) - { - _errorPollingSocket(logger, subchannelId, endPoint, ex); - } - - public static void SocketPollBadState(ILogger logger, string subchannelId, DnsEndPoint endPoint) - { - _socketPollBadState(logger, subchannelId, endPoint, null); - } - - public static void SocketReceivingAvailable(ILogger logger, string subchannelId, DnsEndPoint endPoint, int readBytesAvailableCount) - { - _socketReceivingAvailable(logger, subchannelId, endPoint, readBytesAvailableCount, null); - } - - public static void ClosingUnusableSocket(ILogger logger, string subchannelId, DnsEndPoint endPoint, TimeSpan socketLifetime) - { - _closingUnusableSocket(logger, subchannelId, endPoint, socketLifetime, null); - } - - public static void ClosingSocketFromIdleTimeoutOnCreateStream(ILogger logger, string subchannelId, DnsEndPoint endPoint, TimeSpan socketIdleTimeout) - { - _closingSocketFromIdleTimeoutOnCreateStream(logger, subchannelId, endPoint, socketIdleTimeout, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 17, EventName = "ClosingSocketFromIdleTimeoutOnCreateStream", Message = "Subchannel id '{SubchannelId}' socket {EndPoint} is being closed because it exceeds the idle timeout of {SocketIdleTimeout}.")] + public static partial void ClosingSocketFromIdleTimeoutOnCreateStream(ILogger logger, string subchannelId, DnsEndPoint endPoint, TimeSpan socketIdleTimeout); } #endif diff --git a/src/Grpc.Net.Client/Balancer/PickFirstBalancer.cs b/src/Grpc.Net.Client/Balancer/PickFirstBalancer.cs index 16a8a8f31..88f4cfead 100644 --- a/src/Grpc.Net.Client/Balancer/PickFirstBalancer.cs +++ b/src/Grpc.Net.Client/Balancer/PickFirstBalancer.cs @@ -200,23 +200,18 @@ public override PickResult Pick(PickContext context) } } -internal static class PickFirstBalancerLog +internal static partial class PickFirstBalancerLog { - private static readonly Action _processingSubchannelStateChanged = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "ProcessingSubchannelStateChanged"), "Processing subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'."); - - private static readonly Action _ignoredSubchannelStateChange = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "IgnoredSubchannelStateChange"), "Ignored state change because of unknown subchannel id '{SubchannelId}'."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "ProcessingSubchannelStateChanged", Message = "Processing subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'.")] + private static partial void ProcessingSubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, string Detail, Exception? DebugException); public static void ProcessingSubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, Status status) { - _processingSubchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); + ProcessingSubchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); } - public static void IgnoredSubchannelStateChange(ILogger logger, string subchannelId) - { - _ignoredSubchannelStateChange(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "IgnoredSubchannelStateChange", Message = "Ignored state change because of unknown subchannel id '{SubchannelId}'.")] + public static partial void IgnoredSubchannelStateChange(ILogger logger, string subchannelId); } /// diff --git a/src/Grpc.Net.Client/Balancer/PollingResolver.cs b/src/Grpc.Net.Client/Balancer/PollingResolver.cs index 0973f9339..0f7650d88 100644 --- a/src/Grpc.Net.Client/Balancer/PollingResolver.cs +++ b/src/Grpc.Net.Client/Balancer/PollingResolver.cs @@ -36,7 +36,7 @@ namespace Grpc.Net.Client.Balancer; /// Note: Experimental API that can change or be removed without any prior notice. /// /// -public abstract class PollingResolver : Resolver +public abstract partial class PollingResolver : Resolver { // Internal for testing internal Task _resolveTask = Task.CompletedTask; @@ -256,70 +256,70 @@ protected override void Dispose(bool disposing) _disposed = true; } - internal static class Log + internal static partial class Log { - private static readonly Action _resolverRefreshRequested = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "ResolverRefreshRequested"), "{ResolveType} refresh requested."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "ResolverRefreshRequested", Message = "{ResolveType} refresh requested.")] + private static partial void ResolverRefreshRequested(ILogger logger, string resolveType); - private static readonly Action _resolverRefreshIgnored = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "ResolverRefreshIgnored"), "{ResolveType} refresh ignored because resolve is already in progress."); - - private static readonly Action _resolveError = - LoggerMessage.Define(LogLevel.Error, new EventId(3, "ResolveError"), "Error resolving {ResolveType}."); - - private static readonly Action _resolveResult = - LoggerMessage.Define(LogLevel.Trace, new EventId(4, "ResolveResult"), "{ResolveType} result with status code '{StatusCode}' and {AddressCount} addresses."); - - private static readonly Action _startingResolveBackoff = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "StartingResolveBackoff"), "{ResolveType} starting resolve backoff of {BackoffDuration}."); - - private static readonly Action _errorRetryingResolve = - LoggerMessage.Define(LogLevel.Error, new EventId(6, "ErrorRetryingResolve"), "{ResolveType} error retrying resolve."); - - private static readonly Action _resolveTaskCompleted = - LoggerMessage.Define(LogLevel.Trace, new EventId(7, "ResolveTaskCompleted"), "{ResolveType} resolve task completed."); - - private static readonly Action _resolveStarting = - LoggerMessage.Define(LogLevel.Trace, new EventId(8, "ResolveStarting"), "{ResolveType} resolve starting."); - public static void ResolverRefreshRequested(ILogger logger, Type resolverType) { - _resolverRefreshRequested(logger, resolverType.Name, null); + ResolverRefreshRequested(logger, resolverType.Name); } + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "ResolverRefreshIgnored", Message = "{ResolveType} refresh ignored because resolve is already in progress.")] + private static partial void ResolverRefreshIgnored(ILogger logger, string resolveType); + public static void ResolverRefreshIgnored(ILogger logger, Type resolverType) { - _resolverRefreshIgnored(logger, resolverType.Name, null); + ResolverRefreshIgnored(logger, resolverType.Name); } + [LoggerMessage(Level = LogLevel.Error, EventId = 3, EventName = "ResolveError", Message = "Error resolving {ResolveType}.")] + private static partial void ResolveError(ILogger logger, string resolveType, Exception ex); + public static void ResolveError(ILogger logger, Type resolverType, Exception ex) { - _resolveError(logger, resolverType.Name, ex); + ResolveError(logger, resolverType.Name, ex); } + [LoggerMessage(Level = LogLevel.Trace, EventId = 4, EventName = "ResolveResult", Message = "{ResolveType} result with status code '{StatusCode}' and {AddressCount} addresses.")] + private static partial void ResolveResult(ILogger logger, string resolveType, StatusCode statusCode, int addressCount); + public static void ResolveResult(ILogger logger, Type resolverType, StatusCode statusCode, int addressCount) { - _resolveResult(logger, resolverType.Name, statusCode, addressCount, null); + ResolveResult(logger, resolverType.Name, statusCode, addressCount); } + [LoggerMessage(Level = LogLevel.Trace, EventId = 5, EventName = "StartingResolveBackoff", Message = "{ResolveType} starting resolve backoff of {BackoffDuration}.")] + private static partial void StartingResolveBackoff(ILogger logger, string resolveType, TimeSpan BackoffDuration); + public static void StartingResolveBackoff(ILogger logger, Type resolverType, TimeSpan delay) { - _startingResolveBackoff(logger, resolverType.Name, delay, null); + StartingResolveBackoff(logger, resolverType.Name, delay); } + [LoggerMessage(Level = LogLevel.Error, EventId = 6, EventName = "ErrorRetryingResolve", Message = "{ResolveType} error retrying resolve.")] + private static partial void ErrorRetryingResolve(ILogger logger, string resolveType, Exception ex); + public static void ErrorRetryingResolve(ILogger logger, Type resolverType, Exception ex) { - _errorRetryingResolve(logger, resolverType.Name, ex); + ErrorRetryingResolve(logger, resolverType.Name, ex); } + [LoggerMessage(Level = LogLevel.Trace, EventId = 7, EventName = "ResolveTaskCompleted", Message = "{ResolveType} resolve task completed.")] + private static partial void ResolveTaskCompleted(ILogger logger, string resolveType); + public static void ResolveTaskCompleted(ILogger logger, Type resolverType) { - _resolveTaskCompleted(logger, resolverType.Name, null); + ResolveTaskCompleted(logger, resolverType.Name); } + [LoggerMessage(Level = LogLevel.Trace, EventId = 8, EventName = "ResolveStarting", Message = "{ResolveType} resolve starting.")] + private static partial void ResolveStarting(ILogger logger, string resolveType); + public static void ResolveStarting(ILogger logger, Type resolverType) { - _resolveStarting(logger, resolverType.Name, null); + ResolveStarting(logger, resolverType.Name); } } } diff --git a/src/Grpc.Net.Client/Balancer/Subchannel.cs b/src/Grpc.Net.Client/Balancer/Subchannel.cs index dcfdcd8a5..db0a2ee42 100644 --- a/src/Grpc.Net.Client/Balancer/Subchannel.cs +++ b/src/Grpc.Net.Client/Balancer/Subchannel.cs @@ -544,174 +544,87 @@ public void Dispose() } } -internal static class SubchannelLog +internal static partial class SubchannelLog { - private static readonly Action _subchannelCreated = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "SubchannelCreated"), "Subchannel id '{SubchannelId}' created with addresses: {Addresses}"); - - private static readonly Action _addressesUpdatedWhileConnecting = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "AddressesUpdatedWhileConnecting"), "Subchannel id '{SubchannelId}' is connecting when its addresses are updated. Restarting connect."); - - private static readonly Action _connectedAddressNotInUpdatedAddresses = - LoggerMessage.Define(LogLevel.Debug, new EventId(3, "ConnectedAddressNotInUpdatedAddresses"), "Subchannel id '{SubchannelId}' current address '{CurrentAddress}' is not in the updated addresses."); - - private static readonly Action _connectionRequested = - LoggerMessage.Define(LogLevel.Trace, new EventId(4, "ConnectionRequested"), "Subchannel id '{SubchannelId}' connection requested."); - - private static readonly Action _connectionRequestedInNonIdleState = - LoggerMessage.Define(LogLevel.Debug, new EventId(5, "ConnectionRequestedInNonIdleState"), "Subchannel id '{SubchannelId}' connection requested in non-idle state of {State}."); - - private static readonly Action _connectingTransport = - LoggerMessage.Define(LogLevel.Debug, new EventId(6, "ConnectingTransport"), "Subchannel id '{SubchannelId}' connecting to transport."); - - private static readonly Action _startingConnectBackoff = - LoggerMessage.Define(LogLevel.Trace, new EventId(7, "StartingConnectBackoff"), "Subchannel id '{SubchannelId}' starting connect backoff of {BackoffDuration}."); - - private static readonly Action _connectBackoffInterrupted = - LoggerMessage.Define(LogLevel.Trace, new EventId(8, "ConnectBackoffInterrupted"), "Subchannel id '{SubchannelId}' connect backoff interrupted."); - - private static readonly Action _connectCanceled = - LoggerMessage.Define(LogLevel.Debug, new EventId(9, "ConnectCanceled"), "Subchannel id '{SubchannelId}' connect canceled."); - - private static readonly Action _connectError = - LoggerMessage.Define(LogLevel.Error, new EventId(10, "ConnectError"), "Subchannel id '{SubchannelId}' unexpected error while connecting to transport."); - - private static readonly Action _subchannelStateChanged = - LoggerMessage.Define(LogLevel.Debug, new EventId(11, "SubchannelStateChanged"), "Subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'."); - - private static readonly Action _stateChangedRegistrationCreated = - LoggerMessage.Define(LogLevel.Trace, new EventId(12, "StateChangedRegistrationCreated"), "Subchannel id '{SubchannelId}' state changed registration '{RegistrationId}' created."); - - private static readonly Action _stateChangedRegistrationRemoved = - LoggerMessage.Define(LogLevel.Trace, new EventId(13, "StateChangedRegistrationRemoved"), "Subchannel id '{SubchannelId}' state changed registration '{RegistrationId}' removed."); - - private static readonly Action _executingStateChangedRegistration = - LoggerMessage.Define(LogLevel.Trace, new EventId(14, "ExecutingStateChangedRegistration"), "Subchannel id '{SubchannelId}' executing state changed registration '{RegistrationId}'."); - - private static readonly Action _noStateChangedRegistrations = - LoggerMessage.Define(LogLevel.Trace, new EventId(15, "NoStateChangedRegistrations"), "Subchannel id '{SubchannelId}' has no state changed registrations."); - - private static readonly Action _subchannelPreserved = - LoggerMessage.Define(LogLevel.Trace, new EventId(16, "SubchannelPreserved"), "Subchannel id '{SubchannelId}' matches address '{Address}' and is preserved."); - - private static readonly Action _cancelingConnect = - LoggerMessage.Define(LogLevel.Debug, new EventId(17, "CancelingConnect"), "Subchannel id '{SubchannelId}' canceling connect."); - - private static readonly Action _connectBackoffComplete = - LoggerMessage.Define(LogLevel.Trace, new EventId(18, "ConnectBackoffComplete"), "Subchannel id '{SubchannelId}' connect backoff complete."); - - private static readonly Action _addressesUpdated = - LoggerMessage.Define(LogLevel.Trace, new EventId(19, "AddressesUpdated"), "Subchannel id '{SubchannelId}' updated with addresses: {Addresses}"); - - private static readonly Action _queuingConnect = - LoggerMessage.Define(LogLevel.Debug, new EventId(20, "QueuingConnect"), "Subchannel id '{SubchannelId}' queuing connect because a connect is already in progress."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "SubchannelCreated", Message = "Subchannel id '{SubchannelId}' created with addresses: {Addresses}")] + private static partial void SubchannelCreated(ILogger logger, string subchannelId, string addresses); public static void SubchannelCreated(ILogger logger, string subchannelId, IReadOnlyList addresses) { if (logger.IsEnabled(LogLevel.Debug)) { var addressesText = string.Join(", ", addresses.Select(a => a.EndPoint.Host + ":" + a.EndPoint.Port)); - _subchannelCreated(logger, subchannelId, addressesText, null); + SubchannelCreated(logger, subchannelId, addressesText); } } - public static void AddressesUpdatedWhileConnecting(ILogger logger, string subchannelId) - { - _addressesUpdatedWhileConnecting(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "AddressesUpdatedWhileConnecting", Message = "Subchannel id '{SubchannelId}' is connecting when its addresses are updated. Restarting connect.")] + public static partial void AddressesUpdatedWhileConnecting(ILogger logger, string subchannelId); - public static void ConnectedAddressNotInUpdatedAddresses(ILogger logger, string subchannelId, BalancerAddress currentAddress) - { - _connectedAddressNotInUpdatedAddresses(logger, subchannelId, currentAddress, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 3, EventName = "ConnectedAddressNotInUpdatedAddresses", Message = "Subchannel id '{SubchannelId}' current address '{CurrentAddress}' is not in the updated addresses.")] + public static partial void ConnectedAddressNotInUpdatedAddresses(ILogger logger, string subchannelId, BalancerAddress currentAddress); - public static void ConnectionRequested(ILogger logger, string subchannelId) - { - _connectionRequested(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 4, EventName = "ConnectionRequested", Message = "Subchannel id '{SubchannelId}' connection requested.")] + public static partial void ConnectionRequested(ILogger logger, string subchannelId); - public static void ConnectionRequestedInNonIdleState(ILogger logger, string subchannelId, ConnectivityState state) - { - _connectionRequestedInNonIdleState(logger, subchannelId, state, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 5, EventName = "ConnectionRequestedInNonIdleState", Message = "Subchannel id '{SubchannelId}' connection requested in non-idle state of {State}.")] + public static partial void ConnectionRequestedInNonIdleState(ILogger logger, string subchannelId, ConnectivityState state); - public static void ConnectingTransport(ILogger logger, string subchannelId) - { - _connectingTransport(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 6, EventName = "ConnectingTransport", Message = "Subchannel id '{SubchannelId}' connecting to transport.")] + public static partial void ConnectingTransport(ILogger logger, string subchannelId); - public static void StartingConnectBackoff(ILogger logger, string subchannelId, TimeSpan delay) - { - _startingConnectBackoff(logger, subchannelId, delay, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 7, EventName = "StartingConnectBackoff", Message = "Subchannel id '{SubchannelId}' starting connect backoff of {BackoffDuration}.")] + public static partial void StartingConnectBackoff(ILogger logger, string subchannelId, TimeSpan BackoffDuration); - public static void ConnectBackoffInterrupted(ILogger logger, string subchannelId) - { - _connectBackoffInterrupted(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 8, EventName = "ConnectBackoffInterrupted", Message = "Subchannel id '{SubchannelId}' connect backoff interrupted.")] + public static partial void ConnectBackoffInterrupted(ILogger logger, string subchannelId); - public static void ConnectCanceled(ILogger logger, string subchannelId) - { - _connectCanceled(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 9, EventName = "ConnectCanceled", Message = "Subchannel id '{SubchannelId}' connect canceled.")] + public static partial void ConnectCanceled(ILogger logger, string subchannelId); - public static void ConnectError(ILogger logger, string subchannelId, Exception ex) - { - _connectError(logger, subchannelId, ex); - } + [LoggerMessage(Level = LogLevel.Error, EventId = 10, EventName = "ConnectError", Message = "Subchannel id '{SubchannelId}' unexpected error while connecting to transport.")] + public static partial void ConnectError(ILogger logger, string subchannelId, Exception ex); + + [LoggerMessage(Level = LogLevel.Debug, EventId = 11, EventName = "SubchannelStateChanged", Message = "Subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'.")] + private static partial void SubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, string Detail, Exception? DebugException); public static void SubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, Status status) { - _subchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); + SubchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); } - public static void ExecutingStateChangedRegistration(ILogger logger, string subchannelId, string registrationId) - { - _executingStateChangedRegistration(logger, subchannelId, registrationId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 12, EventName = "StateChangedRegistrationCreated", Message = "Subchannel id '{SubchannelId}' state changed registration '{RegistrationId}' created.")] + public static partial void StateChangedRegistrationCreated(ILogger logger, string subchannelId, string registrationId); - public static void NoStateChangedRegistrations(ILogger logger, string subchannelId) - { - _noStateChangedRegistrations(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 13, EventName = "StateChangedRegistrationRemoved", Message = "Subchannel id '{SubchannelId}' state changed registration '{RegistrationId}' removed.")] + public static partial void StateChangedRegistrationRemoved(ILogger logger, string subchannelId, string registrationId); - public static void StateChangedRegistrationCreated(ILogger logger, string subchannelId, string registrationId) - { - _stateChangedRegistrationCreated(logger, subchannelId, registrationId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 14, EventName = "ExecutingStateChangedRegistration", Message = "Subchannel id '{SubchannelId}' executing state changed registration '{RegistrationId}'.")] + public static partial void ExecutingStateChangedRegistration(ILogger logger, string subchannelId, string registrationId); - public static void StateChangedRegistrationRemoved(ILogger logger, string subchannelId, string registrationId) - { - _stateChangedRegistrationRemoved(logger, subchannelId, registrationId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 15, EventName = "NoStateChangedRegistrations", Message = "Subchannel id '{SubchannelId}' has no state changed registrations.")] + public static partial void NoStateChangedRegistrations(ILogger logger, string subchannelId); - public static void SubchannelPreserved(ILogger logger, string subchannelId, BalancerAddress address) - { - _subchannelPreserved(logger, subchannelId, address, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 16, EventName = "SubchannelPreserved", Message = "Subchannel id '{SubchannelId}' matches address '{Address}' and is preserved.")] + public static partial void SubchannelPreserved(ILogger logger, string subchannelId, BalancerAddress address); - public static void CancelingConnect(ILogger logger, string subchannelId) - { - _cancelingConnect(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 17, EventName = "CancelingConnect", Message = "Subchannel id '{SubchannelId}' canceling connect.")] + public static partial void CancelingConnect(ILogger logger, string subchannelId); - public static void ConnectBackoffComplete(ILogger logger, string subchannelId) - { - _connectBackoffComplete(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 18, EventName = "ConnectBackoffComplete", Message = "Subchannel id '{SubchannelId}' connect backoff complete.")] + public static partial void ConnectBackoffComplete(ILogger logger, string subchannelId); + [LoggerMessage(Level = LogLevel.Trace, EventId = 19, EventName = "AddressesUpdated", Message = "Subchannel id '{SubchannelId}' updated with addresses: {Addresses}")] + private static partial void AddressesUpdated(ILogger logger, string subchannelId, string addresses); public static void AddressesUpdated(ILogger logger, string subchannelId, IReadOnlyList addresses) { if (logger.IsEnabled(LogLevel.Trace)) { var addressesText = string.Join(", ", addresses.Select(a => a.EndPoint.Host + ":" + a.EndPoint.Port)); - _addressesUpdated(logger, subchannelId, addressesText, null); + AddressesUpdated(logger, subchannelId, addressesText); } } - - public static void QueuingConnect(ILogger logger, string subchannelId) - { - _queuingConnect(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 20, EventName = "QueuingConnect", Message = "Subchannel id '{SubchannelId}' queuing connect because a connect is already in progress.")] + public static partial void QueuingConnect(ILogger logger, string subchannelId); } #endif diff --git a/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs b/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs index f5fccf828..5f27c347b 100644 --- a/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs +++ b/src/Grpc.Net.Client/Balancer/SubchannelsLoadBalancer.cs @@ -336,56 +336,36 @@ public void UpdateKnownState(ConnectivityState knownState) } } -internal static class SubchannelsLoadBalancerLog +internal static partial class SubchannelsLoadBalancerLog { - private static readonly Action _processingSubchannelStateChanged = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "ProcessingSubchannelStateChanged"), "Processing subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'."); - - private static readonly Action _ignoredSubchannelStateChange = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "IgnoredSubchannelStateChange"), "Ignored state change because of unknown subchannel id '{SubchannelId}'."); - - private static readonly Action _connectionsUnchanged = - LoggerMessage.Define(LogLevel.Trace, new EventId(3, "ConnectionsUnchanged"), "Connections unchanged."); - - private static readonly Action _refreshingResolverForSubchannel = - LoggerMessage.Define(LogLevel.Trace, new EventId(4, "RefreshingResolverForSubchannel"), "Refreshing resolver because subchannel id '{SubchannelId}' is in state {State}."); - - private static readonly Action _requestingConnectionForSubchannel = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "RequestingConnectionForSubchannel"), "Requesting connection for subchannel id '{SubchannelId}' because it is in state {State}."); - - private static readonly Action _creatingReadyPicker = - LoggerMessage.Define(LogLevel.Trace, new EventId(6, "CreatingReadyPicker"), "Creating ready picker with {SubchannelCount} subchannels: {Subchannels}"); + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "ProcessingSubchannelStateChanged", Message = "Processing subchannel id '{SubchannelId}' state changed to {State}. Detail: '{Detail}'.")] + private static partial void ProcessingSubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, string Detail, Exception? DebugException); public static void ProcessingSubchannelStateChanged(ILogger logger, string subchannelId, ConnectivityState state, Status status) { - _processingSubchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); + ProcessingSubchannelStateChanged(logger, subchannelId, state, status.Detail, status.DebugException); } - public static void IgnoredSubchannelStateChange(ILogger logger, string subchannelId) - { - _ignoredSubchannelStateChange(logger, subchannelId, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "IgnoredSubchannelStateChange", Message = "Ignored state change because of unknown subchannel id '{SubchannelId}'.")] + public static partial void IgnoredSubchannelStateChange(ILogger logger, string subchannelId); - public static void ConnectionsUnchanged(ILogger logger) - { - _connectionsUnchanged(logger, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 3, EventName = "ConnectionsUnchanged", Message = "Connections unchanged.")] + public static partial void ConnectionsUnchanged(ILogger logger); - public static void RefreshingResolverForSubchannel(ILogger logger, string subchannelId, ConnectivityState state) - { - _refreshingResolverForSubchannel(logger, subchannelId, state, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 4, EventName = "RefreshingResolverForSubchannel", Message = "Refreshing resolver because subchannel id '{SubchannelId}' is in state {State}.")] + public static partial void RefreshingResolverForSubchannel(ILogger logger, string subchannelId, ConnectivityState state); - public static void RequestingConnectionForSubchannel(ILogger logger, string subchannelId, ConnectivityState state) - { - _requestingConnectionForSubchannel(logger, subchannelId, state, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 5, EventName = "RequestingConnectionForSubchannel", Message = "Requesting connection for subchannel id '{SubchannelId}' because it is in state {State}.")] + public static partial void RequestingConnectionForSubchannel(ILogger logger, string subchannelId, ConnectivityState state); + + [LoggerMessage(Level = LogLevel.Trace, EventId = 6, EventName = "CreatingReadyPicker", Message = "Creating ready picker with {SubchannelCount} subchannels: {Subchannels}")] + private static partial void CreatingReadyPicker(ILogger logger, int subchannelCount, string subchannels); public static void CreatingReadyPicker(ILogger logger, List readySubchannels) { if (logger.IsEnabled(LogLevel.Trace)) { - _creatingReadyPicker(logger, readySubchannels.Count, string.Join(", ", readySubchannels.Select(s => $"id '{s.Id}' ({string.Join(",", s.GetAddresses())})")), null); + CreatingReadyPicker(logger, readySubchannels.Count, string.Join(", ", readySubchannels.Select(s => $"id '{s.Id}' ({string.Join(",", s.GetAddresses())})"))); } } } diff --git a/src/Grpc.Net.Client/GrpcChannel.cs b/src/Grpc.Net.Client/GrpcChannel.cs index e046854a1..05e170e04 100644 --- a/src/Grpc.Net.Client/GrpcChannel.cs +++ b/src/Grpc.Net.Client/GrpcChannel.cs @@ -39,7 +39,7 @@ namespace Grpc.Net.Client; /// a remote call so in general you should reuse a single channel for as many calls as possible. /// [DebuggerDisplay("{DebuggerToString(),nq}")] -public sealed class GrpcChannel : ChannelBase, IDisposable +public sealed partial class GrpcChannel : ChannelBase, IDisposable { internal const int DefaultMaxReceiveMessageSize = 1024 * 1024 * 4; // 4 MB #if SUPPORT_LOAD_BALANCING @@ -934,15 +934,10 @@ public override int GetHashCode() => (Method != null ? StringComparer.Ordinal.GetHashCode(Method) : 0); } - private static class Log + private static partial class Log { - private static readonly Action _addressPathUnused = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "AddressPathUnused"), "The path in the channel's address '{Address}' won't be used when making gRPC calls. A DelegatingHandler can be used to include a path with gRPC calls. See https://aka.ms/aspnet/grpc/subdir for details."); - - public static void AddressPathUnused(ILogger logger, string address) - { - _addressPathUnused(logger, address, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "AddressPathUnused", Message = "The path in the channel's address '{Address}' won't be used when making gRPC calls. A DelegatingHandler can be used to include a path with gRPC calls. See https://aka.ms/aspnet/grpc/subdir for details.")] + public static partial void AddressPathUnused(ILogger logger, string address); } private readonly record struct HttpHandlerContext(HttpHandlerType HttpHandlerType, TimeSpan? ConnectTimeout = null, TimeSpan? ConnectionIdleTimeout = null); diff --git a/src/Grpc.Net.Client/Internal/ClientStreamWriterBase.cs b/src/Grpc.Net.Client/Internal/ClientStreamWriterBase.cs index a70049eac..c8b89dddd 100644 --- a/src/Grpc.Net.Client/Internal/ClientStreamWriterBase.cs +++ b/src/Grpc.Net.Client/Internal/ClientStreamWriterBase.cs @@ -76,29 +76,14 @@ protected bool IsWriteInProgressUnsynchronized } } -internal static class ClientStreamWriterBaseLog +internal static partial class ClientStreamWriterBaseLog { - private static readonly Action _completingClientStream = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "CompletingClientStream"), "Completing client stream."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "CompletingClientStream", Message = "Completing client stream.")] + public static partial void CompletingClientStream(ILogger logger); - private static readonly Action _writeMessageError = - LoggerMessage.Define(LogLevel.Error, new EventId(2, "WriteMessageError"), "Error writing message."); + [LoggerMessage(Level = LogLevel.Error, EventId = 2, EventName = "WriteMessageError", Message = "Error writing message.")] + public static partial void WriteMessageError(ILogger logger, Exception ex); - private static readonly Action _completeClientStreamError = - LoggerMessage.Define(LogLevel.Error, new EventId(3, "CompleteClientStreamError"), "Error completing client stream."); - - public static void CompletingClientStream(ILogger logger) - { - _completingClientStream(logger, null); - } - - public static void WriteMessageError(ILogger logger, Exception ex) - { - _writeMessageError(logger, ex); - } - - public static void CompleteClientStreamError(ILogger logger, Exception ex) - { - _completeClientStreamError(logger, ex); - } + [LoggerMessage(Level = LogLevel.Error, EventId = 3, EventName = "CompleteClientStreamError", Message = "Error completing client stream.")] + public static partial void CompleteClientStreamError(ILogger logger, Exception ex); } diff --git a/src/Grpc.Net.Client/Internal/GrpcCallLog.cs b/src/Grpc.Net.Client/Internal/GrpcCallLog.cs index 9404b85f2..7156f6574 100644 --- a/src/Grpc.Net.Client/Internal/GrpcCallLog.cs +++ b/src/Grpc.Net.Client/Internal/GrpcCallLog.cs @@ -21,216 +21,88 @@ namespace Grpc.Net.Client.Internal; -internal static class GrpcCallLog +internal static partial class GrpcCallLog { - private static readonly Action _startingCall = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "StartingCall"), "Starting gRPC call. Method type: '{MethodType}', URI: '{Uri}'."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "StartingCall", Message = "Starting gRPC call. Method type: '{MethodType}', URI: '{Uri}'.")] + public static partial void StartingCall(ILogger logger, MethodType methodType, Uri uri); - private static readonly Action _responseHeadersReceived = - LoggerMessage.Define(LogLevel.Trace, new EventId(2, "ResponseHeadersReceived"), "Response headers received."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 2, EventName = "ResponseHeadersReceived", Message = "Response headers received.")] + public static partial void ResponseHeadersReceived(ILogger logger); - private static readonly Action _grpcStatusError = - LoggerMessage.Define(LogLevel.Information, new EventId(3, "GrpcStatusError"), "Call failed with gRPC error status. Status code: '{StatusCode}', Message: '{StatusMessage}'."); + [LoggerMessage(Level = LogLevel.Information, EventId = 3, EventName = "GrpcStatusError", Message = "Call failed with gRPC error status. Status code: '{StatusCode}', Message: '{StatusMessage}'.")] + public static partial void GrpcStatusError(ILogger logger, StatusCode statusCode, string statusMessage, Exception? debugException); - private static readonly Action _finishedCall = - LoggerMessage.Define(LogLevel.Debug, new EventId(4, "FinishedCall"), "Finished gRPC call."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 4, EventName = "FinishedCall", Message = "Finished gRPC call.")] + public static partial void FinishedCall(ILogger logger); - private static readonly Action _startingDeadlineTimeout = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "StartingDeadlineTimeout"), "Starting deadline timeout. Duration: {DeadlineTimeout}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 5, EventName = "StartingDeadlineTimeout", Message = "Starting deadline timeout. Duration: {DeadlineTimeout}.")] + public static partial void StartingDeadlineTimeout(ILogger logger, TimeSpan deadlineTimeout); - private static readonly Action _errorStartingCall = - LoggerMessage.Define(LogLevel.Debug, new EventId(6, "ErrorStartingCall"), "Error starting gRPC call."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 6, EventName = "ErrorStartingCall", Message = "Error starting gRPC call.")] + public static partial void ErrorStartingCall(ILogger logger); - private static readonly Action _deadlineExceeded = - LoggerMessage.Define(LogLevel.Warning, new EventId(7, "DeadlineExceeded"), "gRPC call deadline exceeded."); + [LoggerMessage(Level = LogLevel.Warning, EventId = 7, EventName = "DeadlineExceeded", Message = "gRPC call deadline exceeded.")] + public static partial void DeadlineExceeded(ILogger logger); - private static readonly Action _canceledCall = - LoggerMessage.Define(LogLevel.Debug, new EventId(8, "CanceledCall"), "gRPC call canceled."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 8, EventName = "CanceledCall", Message = "gRPC call canceled.")] + public static partial void CanceledCall(ILogger logger); - private static readonly Action _messageNotReturned = - LoggerMessage.Define(LogLevel.Debug, new EventId(9, "MessageNotReturned"), "Message not returned from unary or client streaming call."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 9, EventName = "MessageNotReturned", Message = "Message not returned from unary or client streaming call.")] + public static partial void MessageNotReturned(ILogger logger); // 10, 11 unused. - private static readonly Action _callCredentialsNotUsed = - LoggerMessage.Define(LogLevel.Warning, new EventId(12, "CallCredentialsNotUsed"), "The configured CallCredentials were not used because the call does not use TLS."); + [LoggerMessage(Level = LogLevel.Warning, EventId = 12, EventName = "CallCredentialsNotUsed", Message = "The configured CallCredentials were not used because the call does not use TLS.")] + public static partial void CallCredentialsNotUsed(ILogger logger); - private static readonly Action _readingMessage = - LoggerMessage.Define(LogLevel.Debug, new EventId(13, "ReadingMessage"), "Reading message."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 13, EventName = "ReadingMessage", Message = "Reading message.")] + public static partial void ReadingMessage(ILogger logger); - private static readonly Action _noMessageReturned = - LoggerMessage.Define(LogLevel.Trace, new EventId(14, "NoMessageReturned"), "No message returned."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 14, EventName = "NoMessageReturned", Message = "No message returned.")] + public static partial void NoMessageReturned(ILogger logger); - private static readonly Action _deserializingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(15, "DeserializingMessage"), "Deserializing {MessageLength} byte message to '{MessageType}'."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 15, EventName = "DeserializingMessage", Message = "Deserializing {MessageLength} byte message to '{MessageType}'.")] + public static partial void DeserializingMessage(ILogger logger, int messageLength, Type messageType); - private static readonly Action _receivedMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(16, "ReceivedMessage"), "Received message."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 16, EventName = "ReceivedMessage", Message = "Received message.")] + public static partial void ReceivedMessage(ILogger logger); - private static readonly Action _errorReadingMessage = - LoggerMessage.Define(LogLevel.Information, new EventId(17, "ErrorReadingMessage"), "Error reading message."); + [LoggerMessage(Level = LogLevel.Information, EventId = 17, EventName = "ErrorReadingMessage", Message = "Error reading message.")] + public static partial void ErrorReadingMessage(ILogger logger, Exception ex); - private static readonly Action _sendingMessage = - LoggerMessage.Define(LogLevel.Debug, new EventId(18, "SendingMessage"), "Sending message."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 18, EventName = "SendingMessage", Message = "Sending message.")] + public static partial void SendingMessage(ILogger logger); - private static readonly Action _messageSent = - LoggerMessage.Define(LogLevel.Trace, new EventId(19, "MessageSent"), "Message sent."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 19, EventName = "MessageSent", Message = "Message sent.")] + public static partial void MessageSent(ILogger logger); - private static readonly Action _errorSendingMessage = - LoggerMessage.Define(LogLevel.Information, new EventId(20, "ErrorSendingMessage"), "Error sending message."); + [LoggerMessage(Level = LogLevel.Information, EventId = 20, EventName = "ErrorSendingMessage", Message = "Error sending message.")] + public static partial void ErrorSendingMessage(ILogger logger, Exception ex); - private static readonly Action _serializedMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(21, "SerializedMessage"), "Serialized '{MessageType}' to {MessageLength} byte message."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 21, EventName = "SerializedMessage", Message = "Serialized '{MessageType}' to {MessageLength} byte message.")] + public static partial void SerializedMessage(ILogger logger, Type messageType, int messageLength); - private static readonly Action _compressingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(22, "CompressingMessage"), "Compressing message with '{MessageEncoding}' encoding."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 22, EventName = "CompressingMessage", Message = "Compressing message with '{MessageEncoding}' encoding.")] + public static partial void CompressingMessage(ILogger logger, string messageEncoding); - private static readonly Action _decompressingMessage = - LoggerMessage.Define(LogLevel.Trace, new EventId(23, "DecompressingMessage"), "Decompressing message with '{MessageEncoding}' encoding."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 23, EventName = "DecompressingMessage", Message = "Decompressing message with '{MessageEncoding}' encoding.")] + public static partial void DecompressingMessage(ILogger logger, string messageEncoding); - private static readonly Action _deadlineTimeoutTooLong = - LoggerMessage.Define(LogLevel.Debug, new EventId(24, "DeadlineTimeoutTooLong"), "Deadline timeout {Timeout} is above maximum allowed timeout of 99999999 seconds. Maximum timeout will be used."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 24, EventName = "DeadlineTimeoutTooLong", Message = "Deadline timeout {Timeout} is above maximum allowed timeout of 99999999 seconds. Maximum timeout will be used.")] + public static partial void DeadlineTimeoutTooLong(ILogger logger, TimeSpan timeout); - private static readonly Action _deadlineTimerRescheduled = - LoggerMessage.Define(LogLevel.Trace, new EventId(25, "DeadlineTimerRescheduled"), "Deadline timer triggered but {Remaining} remaining before deadline exceeded. Deadline timer rescheduled."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 25, EventName = "DeadlineTimerRescheduled", Message = "Deadline timer triggered but {Remaining} remaining before deadline exceeded. Deadline timer rescheduled.")] + public static partial void DeadlineTimerRescheduled(ILogger logger, TimeSpan remaining); - private static readonly Action _errorParsingTrailers = - LoggerMessage.Define(LogLevel.Error, new EventId(26, "ErrorParsingTrailers"), "Error parsing trailers."); + [LoggerMessage(Level = LogLevel.Error, EventId = 26, EventName = "ErrorParsingTrailers", Message = "Error parsing trailers.")] + public static partial void ErrorParsingTrailers(ILogger logger, Exception ex); - private static readonly Action _errorExceedingDeadline = - LoggerMessage.Define(LogLevel.Error, new EventId(27, "ErrorExceedingDeadline"), "Error exceeding deadline."); + [LoggerMessage(Level = LogLevel.Error, EventId = 27, EventName = "ErrorExceedingDeadline", Message = "Error exceeding deadline.")] + public static partial void ErrorExceedingDeadline(ILogger logger, Exception ex); - private static readonly Action _invalidGrpcStatusInHeader = - LoggerMessage.Define(LogLevel.Error, new EventId(28, "InvalidGrpcStatusInHeader"), "Header contains an OK gRPC status. This is invalid for unary or client streaming calls because a status in the header indicates there is no response body. " + - "A message in the response body is required for unary and client streaming calls."); + [LoggerMessage(Level = LogLevel.Error, EventId = 28, EventName = "InvalidGrpcStatusInHeader", + Message = "Header contains an OK gRPC status. This is invalid for unary or client streaming calls because a status in the header indicates there is no response body." + + " A message in the response body is required for unary and client streaming calls.")] + public static partial void InvalidGrpcStatusInHeader(ILogger logger); - public static void StartingCall(ILogger logger, MethodType methodType, Uri uri) - { - _startingCall(logger, methodType, uri, null); - } - - public static void ResponseHeadersReceived(ILogger logger) - { - _responseHeadersReceived(logger, null); - } - - public static void GrpcStatusError(ILogger logger, StatusCode status, string message, Exception? debugException) - { - _grpcStatusError(logger, status, message, debugException); - } - - public static void FinishedCall(ILogger logger) - { - _finishedCall(logger, null); - } - - public static void StartingDeadlineTimeout(ILogger logger, TimeSpan deadlineTimeout) - { - _startingDeadlineTimeout(logger, deadlineTimeout, null); - } - - public static void ErrorStartingCall(ILogger logger) - { - _errorStartingCall(logger, null); - } - - public static void DeadlineExceeded(ILogger logger) - { - _deadlineExceeded(logger, null); - } - - public static void CanceledCall(ILogger logger) - { - _canceledCall(logger, null); - } - - public static void MessageNotReturned(ILogger logger) - { - _messageNotReturned(logger, null); - } - - public static void CallCredentialsNotUsed(ILogger logger) - { - _callCredentialsNotUsed(logger, null); - } - - public static void ReadingMessage(ILogger logger) - { - _readingMessage(logger, null); - } - - public static void NoMessageReturned(ILogger logger) - { - _noMessageReturned(logger, null); - } - - public static void DeserializingMessage(ILogger logger, int messageLength, Type messageType) - { - _deserializingMessage(logger, messageLength, messageType, null); - } - - public static void ReceivedMessage(ILogger logger) - { - _receivedMessage(logger, null); - } - - public static void ErrorReadingMessage(ILogger logger, Exception ex) - { - _errorReadingMessage(logger, ex); - } - - public static void SendingMessage(ILogger logger) - { - _sendingMessage(logger, null); - } - - public static void MessageSent(ILogger logger) - { - _messageSent(logger, null); - } - - public static void ErrorSendingMessage(ILogger logger, Exception ex) - { - _errorSendingMessage(logger, ex); - } - - public static void SerializedMessage(ILogger logger, Type messageType, int messageLength) - { - _serializedMessage(logger, messageType, messageLength, null); - } - - public static void CompressingMessage(ILogger logger, string messageEncoding) - { - _compressingMessage(logger, messageEncoding, null); - } - - public static void DecompressingMessage(ILogger logger, string messageEncoding) - { - _decompressingMessage(logger, messageEncoding, null); - } - - public static void DeadlineTimeoutTooLong(ILogger logger, TimeSpan timeout) - { - _deadlineTimeoutTooLong(logger, timeout, null); - } - - public static void DeadlineTimerRescheduled(ILogger logger, TimeSpan remaining) - { - _deadlineTimerRescheduled(logger, remaining, null); - } - - public static void ErrorParsingTrailers(ILogger logger, Exception ex) - { - _errorParsingTrailers(logger, ex); - } - - public static void ErrorExceedingDeadline(ILogger logger, Exception ex) - { - _errorExceedingDeadline(logger, ex); - } - - public static void InvalidGrpcStatusInHeader(ILogger logger) - { - _invalidGrpcStatusInHeader(logger, null); - } } diff --git a/src/Grpc.Net.Client/Internal/HttpContentClientStreamReader.cs b/src/Grpc.Net.Client/Internal/HttpContentClientStreamReader.cs index d38002909..7ec3a1534 100644 --- a/src/Grpc.Net.Client/Internal/HttpContentClientStreamReader.cs +++ b/src/Grpc.Net.Client/Internal/HttpContentClientStreamReader.cs @@ -275,13 +275,8 @@ public HttpContentClientStreamReaderDebugView(HttpContentClientStreamReader _readMessageError = - LoggerMessage.Define(LogLevel.Error, new EventId(1, "ReadMessageError"), "Error reading message."); - - public static void ReadMessageError(ILogger logger, Exception ex) - { - _readMessageError(logger, ex); - } + [LoggerMessage(Level = LogLevel.Error, EventId = 1, EventName = "ReadMessageError", Message = "Error reading message.")] + public static partial void ReadMessageError(ILogger logger, Exception ex); } diff --git a/src/Grpc.Net.Client/Internal/Retry/ChannelRetryThrottling.cs b/src/Grpc.Net.Client/Internal/Retry/ChannelRetryThrottling.cs index 2cbe4d3fd..17c52c84a 100644 --- a/src/Grpc.Net.Client/Internal/Retry/ChannelRetryThrottling.cs +++ b/src/Grpc.Net.Client/Internal/Retry/ChannelRetryThrottling.cs @@ -21,7 +21,7 @@ namespace Grpc.Net.Client.Internal.Retry; -internal class ChannelRetryThrottling +internal partial class ChannelRetryThrottling { private readonly object _lock = new object(); private readonly double _tokenRatio; @@ -83,14 +83,9 @@ private void UpdateRetryThrottlingActive() } } - private static class Log + private static partial class Log { - private static readonly Action _retryThrottlingActiveChanged = - LoggerMessage.Define(LogLevel.Trace, new EventId(1, "RetryThrottlingActiveChanged"), "Retry throttling active state changed. New value: {RetryThrottlingActive}"); - - public static void RetryThrottlingActiveChanged(ILogger logger, bool isRetryThrottlingActive) - { - _retryThrottlingActiveChanged(logger, isRetryThrottlingActive, null); - } + [LoggerMessage(Level = LogLevel.Trace, EventId = 1, EventName = "RetryThrottlingActiveChanged", Message = "Retry throttling active state changed. New value: {RetryThrottlingActive}")] + public static partial void RetryThrottlingActiveChanged(ILogger logger, bool retryThrottlingActive); } } diff --git a/src/Grpc.Net.Client/Internal/Retry/RetryCallBaseLog.cs b/src/Grpc.Net.Client/Internal/Retry/RetryCallBaseLog.cs index a06390f73..e5b96c3f2 100644 --- a/src/Grpc.Net.Client/Internal/Retry/RetryCallBaseLog.cs +++ b/src/Grpc.Net.Client/Internal/Retry/RetryCallBaseLog.cs @@ -1,4 +1,4 @@ -#region Copyright notice and license +#region Copyright notice and license // Copyright 2019 The gRPC Authors // @@ -21,109 +21,44 @@ namespace Grpc.Net.Client.Internal.Retry; -internal static class RetryCallBaseLog +internal static partial class RetryCallBaseLog { - private static readonly Action _retryEvaluated = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "RetryEvaluated"), "Evaluated retry for failed gRPC call. Status code: '{StatusCode}', Attempt: {AttemptCount}, Retry: {WillRetry}"); + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "RetryEvaluated", Message = "Evaluated retry for failed gRPC call. Status code: '{StatusCode}', Attempt: {AttemptCount}, Retry: {WillRetry}")] + internal static partial void RetryEvaluated(ILogger logger, StatusCode statusCode, int attemptCount, bool willRetry); - private static readonly Action _retryPushbackReceived = - LoggerMessage.Define(LogLevel.Debug, new EventId(2, "RetryPushbackReceived"), "Retry pushback of '{RetryPushback}' received from the failed gRPC call."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 2, EventName = "RetryPushbackReceived", Message = "Retry pushback of '{RetryPushback}' received from the failed gRPC call.")] + internal static partial void RetryPushbackReceived(ILogger logger, string retryPushback); - private static readonly Action _startingRetryDelay = - LoggerMessage.Define(LogLevel.Trace, new EventId(3, "StartingRetryDelay"), "Starting retry delay of {DelayDuration}."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 3, EventName = "StartingRetryDelay", Message = "Starting retry delay of {DelayDuration}.")] + internal static partial void StartingRetryDelay(ILogger logger, TimeSpan delayDuration); - private static readonly Action _errorRetryingCall = - LoggerMessage.Define(LogLevel.Error, new EventId(4, "ErrorRetryingCall"), "Error retrying gRPC call."); + [LoggerMessage(Level = LogLevel.Error, EventId = 4, EventName = "ErrorRetryingCall", Message = "Error retrying gRPC call.")] + internal static partial void ErrorRetryingCall(ILogger logger, Exception ex); - private static readonly Action _sendingBufferedMessages = - LoggerMessage.Define(LogLevel.Trace, new EventId(5, "SendingBufferedMessages"), "Sending {MessageCount} buffered messages from previous failed gRPC calls."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 5, EventName = "SendingBufferedMessages", Message = "Sending {MessageCount} buffered messages from previous failed gRPC calls.")] + internal static partial void SendingBufferedMessages(ILogger logger, int messageCount); - private static readonly Action _messageAddedToBuffer = - LoggerMessage.Define(LogLevel.Trace, new EventId(6, "MessageAddedToBuffer"), "Message with {MessageSize} bytes added to the buffer. There are {CallBufferSize} bytes buffered for this call."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 6, EventName = "MessageAddedToBuffer", Message = "Message with {MessageSize} bytes added to the buffer. There are {CallBufferSize} bytes buffered for this call.")] + internal static partial void MessageAddedToBuffer(ILogger logger, int messageSize, long callBufferSize); - private static readonly Action _callCommited = - LoggerMessage.Define(LogLevel.Debug, new EventId(7, "CallCommited"), "Call commited. Reason: {CommitReason}"); + [LoggerMessage(Level = LogLevel.Debug, EventId = 7, EventName = "CallCommited", Message = "Call commited. Reason: {CommitReason}")] + internal static partial void CallCommited(ILogger logger, CommitReason commitReason); - private static readonly Action _startingRetryWorker = - LoggerMessage.Define(LogLevel.Trace, new EventId(8, "StartingRetryWorker"), "Starting retry worker."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 8, EventName = "StartingRetryWorker", Message = "Starting retry worker.")] + internal static partial void StartingRetryWorker(ILogger logger); - private static readonly Action _stoppingRetryWorker = - LoggerMessage.Define(LogLevel.Trace, new EventId(9, "StoppingRetryWorker"), "Stopping retry worker."); + [LoggerMessage(Level = LogLevel.Trace, EventId = 9, EventName = "StoppingRetryWorker", Message = "Stopping retry worker.")] + internal static partial void StoppingRetryWorker(ILogger logger); - private static readonly Action _maxAttemptsLimited = - LoggerMessage.Define(LogLevel.Debug, new EventId(10, "MaxAttemptsLimited"), "The method has {ServiceConfigMaxAttempts} attempts specified in the service config. The number of attempts has been limited by channel configuration to {ChannelMaxAttempts}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 10, EventName = "MaxAttemptsLimited", Message = "The method has {ServiceConfigMaxAttempts} attempts specified in the service config. The number of attempts has been limited by channel configuration to {ChannelMaxAttempts}.")] + internal static partial void MaxAttemptsLimited(ILogger logger, int serviceConfigMaxAttempts, int channelMaxAttempts); - private static readonly Action _additionalCallsBlockedByRetryThrottling = - LoggerMessage.Define(LogLevel.Debug, new EventId(11, "AdditionalCallsBlockedByRetryThrottling"), "Additional calls blocked by retry throttling."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 11, EventName = "AdditionalCallsBlockedByRetryThrottling", Message = "Additional calls blocked by retry throttling.")] + internal static partial void AdditionalCallsBlockedByRetryThrottling(ILogger logger); - private static readonly Action _startingAttempt = - LoggerMessage.Define(LogLevel.Debug, new EventId(12, "StartingAttempt"), "Starting attempt {AttemptCount}."); + [LoggerMessage(Level = LogLevel.Debug, EventId = 12, EventName = "StartingAttempt", Message = "Starting attempt {AttemptCount}.")] + internal static partial void StartingAttempt(ILogger logger, int AttemptCount); - private static readonly Action _canceledRetry = - LoggerMessage.Define(LogLevel.Debug, new EventId(13, "CanceledRetry"), "gRPC retry call canceled."); - - internal static void RetryEvaluated(ILogger logger, StatusCode statusCode, int attemptCount, bool willRetry) - { - _retryEvaluated(logger, statusCode, attemptCount, willRetry, null); - } - - internal static void RetryPushbackReceived(ILogger logger, string retryPushback) - { - _retryPushbackReceived(logger, retryPushback, null); - } - - internal static void StartingRetryDelay(ILogger logger, TimeSpan delayDuration) - { - _startingRetryDelay(logger, delayDuration, null); - } - - internal static void ErrorRetryingCall(ILogger logger, Exception ex) - { - _errorRetryingCall(logger, ex); - } - - internal static void SendingBufferedMessages(ILogger logger, int messageCount) - { - _sendingBufferedMessages(logger, messageCount, null); - } - - internal static void MessageAddedToBuffer(ILogger logger, int messageSize, long callBufferSize) - { - _messageAddedToBuffer(logger, messageSize, callBufferSize, null); - } - - internal static void CallCommited(ILogger logger, CommitReason commitReason) - { - _callCommited(logger, commitReason, null); - } - - internal static void StartingRetryWorker(ILogger logger) - { - _startingRetryWorker(logger, null); - } - - internal static void StoppingRetryWorker(ILogger logger) - { - _stoppingRetryWorker(logger, null); - } - - internal static void MaxAttemptsLimited(ILogger logger, int serviceConfigMaxAttempts, int channelMaxAttempts) - { - _maxAttemptsLimited(logger, serviceConfigMaxAttempts, channelMaxAttempts, null); - } - - internal static void AdditionalCallsBlockedByRetryThrottling(ILogger logger) - { - _additionalCallsBlockedByRetryThrottling(logger, null); - } - - internal static void StartingAttempt(ILogger logger, int attempts) - { - _startingAttempt(logger, attempts, null); - } - - internal static void CanceledRetry(ILogger logger) - { - _canceledRetry(logger, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 13, EventName = "CanceledRetry", Message = "gRPC retry call canceled.")] + internal static partial void CanceledRetry(ILogger logger); } diff --git a/src/Grpc.Net.ClientFactory/Internal/GrpcCallInvokerFactory.cs b/src/Grpc.Net.ClientFactory/Internal/GrpcCallInvokerFactory.cs index 8b46cbb86..b63816785 100644 --- a/src/Grpc.Net.ClientFactory/Internal/GrpcCallInvokerFactory.cs +++ b/src/Grpc.Net.ClientFactory/Internal/GrpcCallInvokerFactory.cs @@ -31,7 +31,7 @@ namespace Grpc.Net.ClientFactory.Internal; internal readonly record struct EntryKey(string Name, Type Type); -internal class GrpcCallInvokerFactory +internal partial class GrpcCallInvokerFactory { private readonly ILoggerFactory _loggerFactory; private readonly IOptionsMonitor _grpcClientFactoryOptionsMonitor; @@ -251,14 +251,9 @@ protected override Task SendAsync(HttpRequestMessage reques } } - private static class Log + private static partial class Log { - private static readonly Action _httpClientActionsPartiallySupported = - LoggerMessage.Define(LogLevel.Debug, new EventId(1, "HttpClientActionsPartiallySupported"), "The ConfigureHttpClient method is used to configure gRPC client '{ClientName}'. ConfigureHttpClient is partially supported when creating gRPC clients and only some HttpClient properties such as BaseAddress and DefaultRequestHeaders are applied to the gRPC client."); - - public static void HttpClientActionsPartiallySupported(ILogger logger, string clientName) - { - _httpClientActionsPartiallySupported(logger, clientName, null); - } + [LoggerMessage(Level = LogLevel.Debug, EventId = 1, EventName = "HttpClientActionsPartiallySupported", Message = "The ConfigureHttpClient method is used to configure gRPC client '{ClientName}'. ConfigureHttpClient is partially supported when creating gRPC clients and only some HttpClient properties such as BaseAddress and DefaultRequestHeaders are applied to the gRPC client.")] + public static partial void HttpClientActionsPartiallySupported(ILogger logger, string clientName); } }