add loggers

This commit is contained in:
Anton Suhorukov 2022-05-11 16:06:29 +03:00
parent 92c6844810
commit 6e39488231
5 changed files with 153 additions and 25 deletions

View File

@ -79,13 +79,13 @@ public class DefaultRabbitMQPersistentConnection
} }
catch (IOException ex) catch (IOException ex)
{ {
_logger.LogCritical(ex, "DefaultRabbitMQPersistentConnection"); _logger.CriticalDefaultRabbitMQPersistentConnection(ex);
} }
} }
public bool TryConnect() public bool TryConnect()
{ {
_logger.LogInformation("RabbitMQ Client is trying to connect"); _logger.InformationRabbitMQTryingConnect();
lock (sync_root) lock (sync_root)
{ {
@ -93,7 +93,7 @@ public class DefaultRabbitMQPersistentConnection
.Or<BrokerUnreachableException>() .Or<BrokerUnreachableException>()
.WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
{ {
_logger.LogWarning("RabbitMQ Client could not connect after {TimeOut}s ({ExceptionMessage})", $"{time.TotalSeconds:n1}", ex.Message); _logger.WarningRabbitMQCouldNotConnect(time.TotalSeconds, ex);
} }
); );
@ -109,13 +109,13 @@ public class DefaultRabbitMQPersistentConnection
_connection.CallbackException += OnCallbackException; _connection.CallbackException += OnCallbackException;
_connection.ConnectionBlocked += OnConnectionBlocked; _connection.ConnectionBlocked += OnConnectionBlocked;
_logger.LogInformation("RabbitMQ Client acquired a persistent connection to '{HostName}' and is subscribed to failure events", _connection.Endpoint.HostName); _logger.InformationRabbitMQAcquiredPersistentConnection(_connection.Endpoint.HostName);
return true; return true;
} }
else else
{ {
_logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened"); _logger.CriticalRabbitMQCouldNotBeCreated();
return false; return false;
} }
@ -129,7 +129,7 @@ public class DefaultRabbitMQPersistentConnection
return; return;
} }
_logger.LogWarning("A RabbitMQ connection is shutdown. Trying to re-connect..."); _logger.WarningRabbitMQConnectionShutdown();
TryConnect(); TryConnect();
} }
@ -141,7 +141,7 @@ public class DefaultRabbitMQPersistentConnection
return; return;
} }
_logger.LogWarning("A RabbitMQ connection throw exception. Trying to re-connect..."); _logger.WarningRabbitMQConnectionThrowException();
TryConnect(); TryConnect();
} }
@ -153,7 +153,7 @@ public class DefaultRabbitMQPersistentConnection
return; return;
} }
_logger.LogWarning("A RabbitMQ connection is on shutdown. Trying to re-connect..."); _logger.WarningRabbitMQConnectionIsOnShutDown();
TryConnect(); TryConnect();
} }

View File

@ -105,16 +105,16 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
.Or<SocketException>() .Or<SocketException>()
.WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
{ {
_logger.LogWarning(ex, string.Format("Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", @event.Id, $"{time.TotalSeconds:n1}", ex.Message)); _logger.WarningCouldNotPublishEvent(@event.Id, time.TotalSeconds, ex);
}); });
var eventName = @event.GetType().Name; var eventName = @event.GetType().Name;
_logger.LogTrace("Creating RabbitMQ channel to publish event: {EventId} ({EventName})", @event.Id, eventName); _logger.TraceCreatingRabbitMQChannel(@event.Id, eventName);
using (var channel = _persistentConnection.CreateModel()) using (var channel = _persistentConnection.CreateModel())
{ {
_logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", @event.Id); _logger.TraceDeclaringRabbitMQChannel(@event.Id);
channel.ExchangeDeclare(exchange: EXCHANGE_NAME, type: "direct"); channel.ExchangeDeclare(exchange: EXCHANGE_NAME, type: "direct");
@ -125,7 +125,7 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
var properties = channel.CreateBasicProperties(); var properties = channel.CreateBasicProperties();
properties.DeliveryMode = 2; // persistent properties.DeliveryMode = 2; // persistent
_logger.LogTrace("Publishing event to RabbitMQ: {EventId}", @event.Id); _logger.TracePublishingEvent(@event.Id);
channel.BasicPublish( channel.BasicPublish(
exchange: EXCHANGE_NAME, exchange: EXCHANGE_NAME,
@ -140,7 +140,7 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
public void SubscribeDynamic<TH>(string eventName) public void SubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler where TH : IDynamicIntegrationEventHandler
{ {
_logger.LogInformation("Subscribing to dynamic event {EventName} with {EventHandler}", eventName, typeof(TH).GetGenericTypeName()); _logger.InformationSubscribingDynamic(eventName, typeof(TH).GetGenericTypeName());
DoInternalSubscription(eventName); DoInternalSubscription(eventName);
_subsManager.AddDynamicSubscription<TH>(eventName); _subsManager.AddDynamicSubscription<TH>(eventName);
@ -154,7 +154,7 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
var eventName = _subsManager.GetEventKey<T>(); var eventName = _subsManager.GetEventKey<T>();
DoInternalSubscription(eventName); DoInternalSubscription(eventName);
_logger.LogInformation("Subscribing to event {EventName} with {EventHandler}", eventName, typeof(TH).GetGenericTypeName()); _logger.InformationSubscribing(eventName, typeof(TH).GetGenericTypeName());
_subsManager.AddSubscription<T, TH>(); _subsManager.AddSubscription<T, TH>();
StartBasicConsume(); StartBasicConsume();
@ -209,13 +209,13 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
private void StartBasicConsume() private void StartBasicConsume()
{ {
_logger.LogTrace("Starting RabbitMQ basic consume"); _logger.TraceStartingBasicConsume();
if (_consumerChannel != null) if (_consumerChannel != null)
{ {
if (!String.IsNullOrEmpty(_consumerTag)) if (!String.IsNullOrEmpty(_consumerTag))
{ {
_logger.LogTrace("Consumer tag {ConsumerTag} already exist. Cancelled BasicConsume again", _consumerTag); _logger.TraceConsumerTagExist(_consumerTag);
return; return;
} }
@ -231,7 +231,7 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
} }
else else
{ {
_logger.LogError("StartBasicConsume can't call on _consumerChannel == null"); _logger.ErrorStartBasicConsumeCantCall();
} }
} }
@ -255,7 +255,7 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
} }
catch (IntegrationEventRejectExeption ex) catch (IntegrationEventRejectExeption ex)
{ {
_logger.LogWarning(ex, string.Format("----- ERROR Processing message \"{0}\"", message)); _logger.WarningProcessingMessage(message, ex);
if (eventArgs.Redelivered) if (eventArgs.Redelivered)
{ {
@ -275,8 +275,8 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning(ex, string.Format("----- ERROR Processing message \"{0}\"", message)); _logger.WarningProcessingMessage(message, ex);
_consumerChannel.BasicAck(eventArgs.DeliveryTag, multiple: false); _consumerChannel.BasicAck(eventArgs.DeliveryTag, multiple: false);
} }
@ -289,7 +289,7 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
_persistentConnection.TryConnect(); _persistentConnection.TryConnect();
} }
_logger.LogTrace("Creating RabbitMQ consumer channel"); _logger.TraceCreatingConsumerChannel();
var channel = _persistentConnection.CreateModel(); var channel = _persistentConnection.CreateModel();
@ -318,7 +318,7 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
channel.CallbackException += (sender, ea) => channel.CallbackException += (sender, ea) =>
{ {
_logger.LogWarning(ea.Exception, "Recreating RabbitMQ consumer channel"); _logger.WarningRecreatingConsumerChannel(ea.Exception);
_consumerChannel.Dispose(); _consumerChannel.Dispose();
_consumerChannel = CreateConsumerChannel(); _consumerChannel = CreateConsumerChannel();
@ -354,7 +354,7 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
private async Task ProcessEvent(string eventName, IntegrationEvent @event) private async Task ProcessEvent(string eventName, IntegrationEvent @event)
{ {
_logger.LogTrace("Processing RabbitMQ event: {EventName}", eventName); _logger.TraceProcessingEvent(eventName);
PreProcessEvent(@event); PreProcessEvent(@event);
@ -397,7 +397,7 @@ public class EventBusRabbitMQ : IEventBus, IDisposable
} }
else else
{ {
_logger.LogWarning("No subscription for RabbitMQ event: {EventName}", eventName); _logger.WarningNoSubscription(eventName);
} }
} }
} }

View File

@ -29,6 +29,7 @@ global using System.Net.Sockets;
global using ASC.EventBus.Abstractions; global using ASC.EventBus.Abstractions;
global using ASC.EventBus.Events; global using ASC.EventBus.Events;
global using ASC.EventBus.Extensions; global using ASC.EventBus.Extensions;
global using ASC.EventBus.RabbitMQ.Log;
global using Autofac; global using Autofac;
@ -36,6 +37,6 @@ global using Microsoft.Extensions.Logging;
global using Polly; global using Polly;
global using RabbitMQ.Client; global using RabbitMQ.Client;
global using RabbitMQ.Client.Events; global using RabbitMQ.Client.Events;
global using RabbitMQ.Client.Exceptions; global using RabbitMQ.Client.Exceptions;

View File

@ -0,0 +1,53 @@
// (c) Copyright Ascensio System SIA 2010-2022
//
// This program is a free software product.
// You can redistribute it and/or modify it under the terms
// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software
// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended
// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of
// any third-party rights.
//
// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see
// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
//
// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021.
//
// The interactive user interfaces in modified source and object code versions of the Program must
// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3.
//
// Pursuant to Section 7(b) of the License you must retain the original Product logo when
// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under
// trademark law for use of our trademarks.
//
// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing
// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
namespace ASC.EventBus.RabbitMQ.Log;
internal static partial class DefaultRabbitMQPersistentConnectionLogger
{
[LoggerMessage(Level = LogLevel.Critical, Message = "DefaultRabbitMQPersistentConnection")]
public static partial void CriticalDefaultRabbitMQPersistentConnection(this ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Information, Message = "RabbitMQ Client is trying to connect")]
public static partial void InformationRabbitMQTryingConnect(this ILogger logger);
[LoggerMessage(Level = LogLevel.Warning, Message = "RabbitMQ Client could not connect after {timeOut}s")]
public static partial void WarningRabbitMQCouldNotConnect(this ILogger logger, double timeOut, Exception exception);
[LoggerMessage(Level = LogLevel.Information, Message = "RabbitMQ Client acquired a persistent connection to '{hostName}' and is subscribed to failure events")]
public static partial void InformationRabbitMQAcquiredPersistentConnection(this ILogger logger, string hostName);
[LoggerMessage(Level = LogLevel.Critical, Message = "FATAL ERROR: RabbitMQ connections could not be created and opened")]
public static partial void CriticalRabbitMQCouldNotBeCreated(this ILogger logger);
[LoggerMessage(Level = LogLevel.Warning, Message = "A RabbitMQ connection is shutdown. Trying to re-connect...")]
public static partial void WarningRabbitMQConnectionShutdown(this ILogger logger);
[LoggerMessage(Level = LogLevel.Warning, Message = "A RabbitMQ connection throw exception. Trying to re-connect...")]
public static partial void WarningRabbitMQConnectionThrowException(this ILogger logger);
[LoggerMessage(Level = LogLevel.Warning, Message = "A RabbitMQ connection is on shutdown. Trying to re-connect...")]
public static partial void WarningRabbitMQConnectionIsOnShutDown(this ILogger logger);
}

View File

@ -0,0 +1,74 @@
// (c) Copyright Ascensio System SIA 2010-2022
//
// This program is a free software product.
// You can redistribute it and/or modify it under the terms
// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software
// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended
// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of
// any third-party rights.
//
// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see
// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
//
// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021.
//
// The interactive user interfaces in modified source and object code versions of the Program must
// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3.
//
// Pursuant to Section 7(b) of the License you must retain the original Product logo when
// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under
// trademark law for use of our trademarks.
//
// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing
// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
namespace ASC.EventBus.RabbitMQ.Log;
internal static partial class EventBusRabbitMQLogger
{
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not publish event: {eventId} after {timeout}s")]
public static partial void WarningCouldNotPublishEvent(this ILogger logger, Guid eventId, double timeout, Exception exception);
[LoggerMessage(Level = LogLevel.Trace, Message = "Creating RabbitMQ channel to publish event: {eventId} ({eventName})")]
public static partial void TraceCreatingRabbitMQChannel(this ILogger logger, Guid eventId, string eventName);
[LoggerMessage(Level = LogLevel.Trace, Message = "Declaring RabbitMQ exchange to publish event: {eventId}")]
public static partial void TraceDeclaringRabbitMQChannel(this ILogger logger, Guid eventId);
[LoggerMessage(Level = LogLevel.Trace, Message = "Publishing event to RabbitMQ: {eventId}")]
public static partial void TracePublishingEvent(this ILogger logger, Guid eventId);
[LoggerMessage(Level = LogLevel.Information, Message = "Subscribing to dynamic event {eventName} with {eventHandler}")]
public static partial void InformationSubscribingDynamic(this ILogger logger, string eventName, string eventHandler);
[LoggerMessage(Level = LogLevel.Information, Message = "Subscribing to event {eventName} with {eventHandler}")]
public static partial void InformationSubscribing(this ILogger logger, string eventName, string eventHandler);
[LoggerMessage(Level = LogLevel.Information, Message = "Unsubscribing from event {eventName}")]
public static partial void InformationUnsubscribing(this ILogger logger, string eventName);
[LoggerMessage(Level = LogLevel.Trace, Message = "Starting RabbitMQ basic consume")]
public static partial void TraceStartingBasicConsume(this ILogger logger);
[LoggerMessage(Level = LogLevel.Trace, Message = "Consumer tag {consumerTag} already exist. Cancelled BasicConsume again")]
public static partial void TraceConsumerTagExist(this ILogger logger, string consumerTag);
[LoggerMessage(Level = LogLevel.Error, Message = "StartBasicConsume can't call on _consumerChannel == null")]
public static partial void ErrorStartBasicConsumeCantCall(this ILogger logger);
[LoggerMessage(Level = LogLevel.Warning, Message = "----- ERROR Processing message \"{message}\"")]
public static partial void WarningProcessingMessage(this ILogger logger, string message, Exception exception);
[LoggerMessage(Level = LogLevel.Trace, Message = "Creating RabbitMQ consumer channel")]
public static partial void TraceCreatingConsumerChannel(this ILogger logger);
[LoggerMessage(Level = LogLevel.Warning, Message = "Recreating RabbitMQ consumer channel")]
public static partial void WarningRecreatingConsumerChannel(this ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Trace, Message = "Processing RabbitMQ event: {eventName}")]
public static partial void TraceProcessingEvent(this ILogger logger, string eventName);
[LoggerMessage(Level = LogLevel.Warning, Message = "No subscription for RabbitMQ event: {eventName}")]
public static partial void WarningNoSubscription(this ILogger logger, string eventName);
}