From 4e9a7be7dde8548da26fe6944770143ef07a475f Mon Sep 17 00:00:00 2001 From: BrennanConroy Date: Wed, 20 Sep 2017 15:13:26 -0700 Subject: [PATCH] SignalR Core Logging (#889) --- .../HubEndPoint.cs | 37 +++--- .../Internal/SignalRCoreLoggerExtensions.cs | 117 ++++++++++++++++++ 2 files changed, 133 insertions(+), 21 deletions(-) create mode 100644 src/Microsoft.AspNetCore.SignalR.Core/Internal/SignalRCoreLoggerExtensions.cs diff --git a/src/Microsoft.AspNetCore.SignalR.Core/HubEndPoint.cs b/src/Microsoft.AspNetCore.SignalR.Core/HubEndPoint.cs index 01e95ea142..1ce35f56a2 100644 --- a/src/Microsoft.AspNetCore.SignalR.Core/HubEndPoint.cs +++ b/src/Microsoft.AspNetCore.SignalR.Core/HubEndPoint.cs @@ -11,6 +11,7 @@ using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Channels; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.SignalR.Core.Internal; using Microsoft.AspNetCore.SignalR.Features; using Microsoft.AspNetCore.SignalR.Internal; using Microsoft.AspNetCore.SignalR.Internal.Encoders; @@ -143,7 +144,7 @@ namespace Microsoft.AspNetCore.SignalR connection.ProtocolReaderWriter = new HubProtocolReaderWriter(protocol, dataEncoder); - _logger.LogInformation("Using HubProtocol '{protocol}'.", protocol.Name); + _logger.UsingHubProtocol(protocol.Name); return true; } @@ -153,7 +154,7 @@ namespace Microsoft.AspNetCore.SignalR } catch (OperationCanceledException) { - _logger.LogDebug("Negotiate was canceled."); + _logger.NegotiateCanceled(); } return false; @@ -169,7 +170,7 @@ namespace Microsoft.AspNetCore.SignalR } catch (Exception ex) { - _logger.LogError(0, ex, "Error when processing requests."); + _logger.ErrorProcessingRequest(ex); await HubOnDisconnectedAsync(connection, ex); throw; } @@ -198,7 +199,7 @@ namespace Microsoft.AspNetCore.SignalR } catch (Exception ex) { - _logger.LogError(0, ex, "Error when invoking OnConnectedAsync on hub."); + _logger.ErrorInvokingHubMethod("OnConnectedAsync", ex); throw; } } @@ -237,7 +238,7 @@ namespace Microsoft.AspNetCore.SignalR } catch (Exception ex) { - _logger.LogError(0, ex, "Error when invoking OnDisconnectedAsync on hub."); + _logger.ErrorInvokingHubMethod("OnDisconnectedAsync", ex); throw; } } @@ -260,10 +261,7 @@ namespace Microsoft.AspNetCore.SignalR switch (hubMessage) { case InvocationMessage invocationMessage: - if (_logger.IsEnabled(LogLevel.Debug)) - { - _logger.LogDebug("Received hub invocation: {invocation}", invocationMessage); - } + _logger.ReceivedHubInvocation(invocationMessage); // Don't wait on the result of execution, continue processing other // incoming messages on this connection. @@ -272,7 +270,7 @@ namespace Microsoft.AspNetCore.SignalR // Other kind of message we weren't expecting default: - _logger.LogError("Received unsupported message of type '{messageType}'", hubMessage.GetType().FullName); + _logger.UnsupportedMessageReceived(hubMessage.GetType().FullName); throw new NotSupportedException($"Received unsupported message: {hubMessage}"); } } @@ -307,7 +305,7 @@ namespace Microsoft.AspNetCore.SignalR if (!_methods.TryGetValue(invocationMessage.Target, out var descriptor)) { // Send an error to the client. Then let the normal completion process occur - _logger.LogError("Unknown hub method '{method}'", invocationMessage.Target); + _logger.UnknownHubMethod(invocationMessage.Target); await SendMessageAsync(connection, CompletionMessage.WithError(invocationMessage.InvocationId, $"Unknown hub method '{invocationMessage.Target}'")); } else @@ -327,7 +325,7 @@ namespace Microsoft.AspNetCore.SignalR } // Output is closed. Cancel this invocation completely - _logger.LogWarning("Outbound channel was closed while trying to write hub message"); + _logger.OutboundChannelClosed(); throw new OperationCanceledException("Outbound channel was closed while trying to write hub message"); } @@ -339,7 +337,7 @@ namespace Microsoft.AspNetCore.SignalR { if (!await IsHubMethodAuthorized(scope.ServiceProvider, connection.User, descriptor.Policies)) { - _logger.LogDebug("Failed to invoke {hubMethod} because user is unauthorized", invocationMessage.Target); + _logger.HubMethodNotAuthorized(invocationMessage.Target); if (!invocationMessage.NonBlocking) { await SendMessageAsync(connection, CompletionMessage.WithError(invocationMessage.InvocationId, $"Failed to invoke '{invocationMessage.Target}' because user is unauthorized")); @@ -375,18 +373,18 @@ namespace Microsoft.AspNetCore.SignalR if (IsStreamed(connection, methodExecutor, result, methodExecutor.MethodReturnType, out var enumerator)) { - _logger.LogTrace("[{connectionId}/{invocationId}] Streaming result of type {resultType}", connection.ConnectionId, invocationMessage.InvocationId, methodExecutor.MethodReturnType.FullName); + _logger.StreamingResult(invocationMessage.InvocationId, methodExecutor.MethodReturnType.FullName); await StreamResultsAsync(invocationMessage.InvocationId, connection, enumerator); } else if (!invocationMessage.NonBlocking) { - _logger.LogTrace("[{connectionId}/{invocationId}] Sending result of type {resultType}", connection.ConnectionId, invocationMessage.InvocationId, methodExecutor.MethodReturnType.FullName); + _logger.SendingResult(invocationMessage.InvocationId, methodExecutor.MethodReturnType.FullName); await SendMessageAsync(connection, CompletionMessage.WithResult(invocationMessage.InvocationId, result)); } } catch (TargetInvocationException ex) { - _logger.LogError(0, ex, "Failed to invoke hub method"); + _logger.FailedInvokingHubMethod(invocationMessage.Target, ex); if (!invocationMessage.NonBlocking) { await SendMessageAsync(connection, CompletionMessage.WithError(invocationMessage.InvocationId, ex.InnerException.Message)); @@ -394,7 +392,7 @@ namespace Microsoft.AspNetCore.SignalR } catch (Exception ex) { - _logger.LogError(0, ex, "Failed to invoke hub method"); + _logger.FailedInvokingHubMethod(invocationMessage.Target, ex); if (!invocationMessage.NonBlocking) { await SendMessageAsync(connection, CompletionMessage.WithError(invocationMessage.InvocationId, ex.Message)); @@ -502,10 +500,7 @@ namespace Microsoft.AspNetCore.SignalR var authorizeAttributes = methodInfo.GetCustomAttributes(inherit: true); _methods[methodName] = new HubMethodDescriptor(executor, authorizeAttributes); - if (_logger.IsEnabled(LogLevel.Debug)) - { - _logger.LogDebug("Hub method '{methodName}' is bound", methodName); - } + _logger.HubMethodBound(methodName); } } diff --git a/src/Microsoft.AspNetCore.SignalR.Core/Internal/SignalRCoreLoggerExtensions.cs b/src/Microsoft.AspNetCore.SignalR.Core/Internal/SignalRCoreLoggerExtensions.cs new file mode 100644 index 0000000000..b02f898834 --- /dev/null +++ b/src/Microsoft.AspNetCore.SignalR.Core/Internal/SignalRCoreLoggerExtensions.cs @@ -0,0 +1,117 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Microsoft.AspNetCore.SignalR.Internal.Protocol; +using Microsoft.Extensions.Logging; + +namespace Microsoft.AspNetCore.SignalR.Core.Internal +{ + internal static class SignalRCoreLoggerExtensions + { + // Category: HubEndPoint + private static readonly Action _usingHubProtocol = + LoggerMessage.Define(LogLevel.Information, 0, "Using HubProtocol '{protocol}'."); + + private static readonly Action _negotiateCanceled = + LoggerMessage.Define(LogLevel.Debug, 1, "Negotiate was canceled."); + + private static readonly Action _errorProcessingRequest = + LoggerMessage.Define(LogLevel.Error, 2, "Error when processing requests."); + + private static readonly Action _errorInvokingHubMethod = + LoggerMessage.Define(LogLevel.Error, 3, "Error when invoking '{hubMethod}' on hub."); + + private static readonly Action _receivedHubInvocation = + LoggerMessage.Define(LogLevel.Debug, 4, "Received hub invocation: {invocationMessage}."); + + private static readonly Action _unsupportedMessageReceived = + LoggerMessage.Define(LogLevel.Error, 5, "Received unsupported message of type '{messageType}'."); + + private static readonly Action _unknownHubMethod = + LoggerMessage.Define(LogLevel.Error, 6, "Unknown hub method '{hubMethod}'."); + + private static readonly Action _outboundChannelClosed = + LoggerMessage.Define(LogLevel.Warning, 7, "Outbound channel was closed while trying to write hub message."); + + private static readonly Action _hubMethodNotAuthorized = + LoggerMessage.Define(LogLevel.Debug, 8, "Failed to invoke '{hubMethod}' because user is unauthorized."); + + private static readonly Action _streamingResult = + LoggerMessage.Define(LogLevel.Trace, 9, "{invocationId}: Streaming result of type '{resultType}'."); + + private static readonly Action _sendingResult = + LoggerMessage.Define(LogLevel.Trace, 10, "{invocationId}: Sending result of type '{resultType}'."); + + private static readonly Action _failedInvokingHubMethod = + LoggerMessage.Define(LogLevel.Error, 11, "Failed to invoke hub method '{hubMethod}'."); + + private static readonly Action _hubMethodBound = + LoggerMessage.Define(LogLevel.Trace, 12, "Hub method '{hubMethod}' is bound."); + + public static void UsingHubProtocol(this ILogger logger, string hubProtocol) + { + _usingHubProtocol(logger, hubProtocol, null); + } + + public static void NegotiateCanceled(this ILogger logger) + { + _negotiateCanceled(logger, null); + } + + public static void ErrorProcessingRequest(this ILogger logger, Exception exception) + { + _errorProcessingRequest(logger, exception); + } + + public static void ErrorInvokingHubMethod(this ILogger logger, string hubMethod, Exception exception) + { + _errorInvokingHubMethod(logger, hubMethod, exception); + } + + public static void ReceivedHubInvocation(this ILogger logger, InvocationMessage invocationMessage) + { + _receivedHubInvocation(logger, invocationMessage, null); + } + + public static void UnsupportedMessageReceived(this ILogger logger, string messageType) + { + _unsupportedMessageReceived(logger, messageType, null); + } + + public static void UnknownHubMethod(this ILogger logger, string hubMethod) + { + _unknownHubMethod(logger, hubMethod, null); + } + + public static void OutboundChannelClosed(this ILogger logger) + { + _outboundChannelClosed(logger, null); + } + + public static void HubMethodNotAuthorized(this ILogger logger, string hubMethod) + { + _hubMethodNotAuthorized(logger, hubMethod, null); + } + + public static void StreamingResult(this ILogger logger, string invocationId, string resultType) + { + _streamingResult(logger, invocationId, resultType, null); + } + + public static void SendingResult(this ILogger logger, string invocationId, string resultType) + { + _sendingResult(logger, invocationId, resultType, null); + } + + public static void FailedInvokingHubMethod(this ILogger logger, string hubMethod, Exception exception) + { + _failedInvokingHubMethod(logger, hubMethod, exception); + } + + public static void HubMethodBound(this ILogger logger, string hubMethod) + { + _hubMethodBound(logger, hubMethod, null); + } + } +} \ No newline at end of file