Fixed logging call inside main lib

This commit is contained in:
2025-08-03 03:42:27 +04:00
parent a87a07d939
commit 1e0b5078c6
11 changed files with 82 additions and 46 deletions
@@ -34,11 +34,11 @@ namespace Telegrator.Hosting.Logging
if (exception != null) if (exception != null)
{ {
_logger.Log(msLogLevel, default, exception, message); _logger.Log(msLogLevel, default, message, exception, (str, exc) => string.Format("{0} : {1}", str, exc));
} }
else else
{ {
_logger.Log(msLogLevel, message); _logger.Log(msLogLevel, default, message, null, (str, _) => str);
} }
} }
} }
@@ -6,18 +6,6 @@
/// </summary> /// </summary>
public interface ITelegratorOptions public interface ITelegratorOptions
{ {
/*
/// <summary>
/// Gets or sets a value indicating whether only the first found handler should be executed for each update.
/// </summary>
public bool ExecuteOnlyFirstFoundHanlder { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to descend the indexr of handler's index on register. ('false' by default)
/// </summary>
public bool DescendDescriptorIndex { get; set; }
*/
/// <summary> /// <summary>
/// Gets or sets the maximum number of parallel working handlers. Null means no limit. /// Gets or sets the maximum number of parallel working handlers. Null means no limit.
/// </summary> /// </summary>
@@ -1,5 +1,6 @@
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegrator.Logging;
namespace Telegrator.Filters.Components namespace Telegrator.Filters.Components
{ {
@@ -47,7 +48,7 @@ namespace Telegrator.Filters.Components
if (!filter.CanPass(context)) if (!filter.CanPass(context))
{ {
if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter) if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter)
Alligator.FilterWriteLine("(E) {0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]); Alligator.LogDebug("{0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]);
return false; return false;
} }
@@ -1,4 +1,5 @@
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegrator.Logging;
namespace Telegrator.Filters.Components namespace Telegrator.Filters.Components
{ {
@@ -49,7 +50,7 @@ namespace Telegrator.Filters.Components
if (!filter.CanPass(context)) if (!filter.CanPass(context))
{ {
if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter) if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter)
Alligator.FilterWriteLine("(E) {0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]); Alligator.LogDebug("{0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]);
return false; return false;
} }
@@ -1,4 +1,6 @@
namespace Telegrator.Filters.Components using Telegrator.Logging;
namespace Telegrator.Filters.Components
{ {
/// <summary> /// <summary>
/// Represents a filter that composes multiple filters and passes only if all of them pass. /// Represents a filter that composes multiple filters and passes only if all of them pass.
@@ -39,7 +41,7 @@
if (!filter.CanPass(context)) if (!filter.CanPass(context))
{ {
if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter) if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter)
Alligator.FilterWriteLine("(E) {0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]); Alligator.LogDebug("{0} filter of {1} didnt pass!", filter.GetType().Name, context.Data["handler_name"]);
return false; return false;
} }
+49
View File
@@ -14,6 +14,12 @@ namespace Telegrator.Logging
/// </summary> /// </summary>
public static int AdaptersCount => _adapters.Count; public static int AdaptersCount => _adapters.Count;
/// <summary>
/// Minimal level of logging messages.
/// Any messages below thi value will not be writen!
/// </summary>
public static LogLevel MinimalLevel { get; set; }
/// <summary> /// <summary>
/// Adds a logger adapter to the centralized logging system. /// Adds a logger adapter to the centralized logging system.
/// </summary> /// </summary>
@@ -70,6 +76,9 @@ namespace Telegrator.Logging
if (_adapters.Count == 0) if (_adapters.Count == 0)
return; return;
if (level < MinimalLevel)
return;
// Lock only during enumeration to prevent collection modification during iteration // Lock only during enumeration to prevent collection modification during iteration
lock (_lock) lock (_lock)
{ {
@@ -105,6 +114,16 @@ namespace Telegrator.Logging
Log(LogLevel.Debug, message); Log(LogLevel.Debug, message);
} }
/// <summary>
/// Logs a debug message to all registered adapters.
/// </summary>
/// <param name="message">The message to log.</param>
/// <param name="args"></param>
public static void LogDebug(string message, params object[] args)
{
Log(LogLevel.Debug, string.Format(message, args));
}
/// <summary> /// <summary>
/// Logs an information message to all registered adapters. /// Logs an information message to all registered adapters.
/// </summary> /// </summary>
@@ -114,6 +133,16 @@ namespace Telegrator.Logging
Log(LogLevel.Information, message); Log(LogLevel.Information, message);
} }
/// <summary>
/// Logs an information message to all registered adapters.
/// </summary>
/// <param name="message">The message to log.</param>
/// <param name="args"></param>
public static void LogInformation(string message, params object[] args)
{
Log(LogLevel.Information, string.Format(message, args));
}
/// <summary> /// <summary>
/// Logs a warning message to all registered adapters. /// Logs a warning message to all registered adapters.
/// </summary> /// </summary>
@@ -123,6 +152,16 @@ namespace Telegrator.Logging
Log(LogLevel.Warning, message); Log(LogLevel.Warning, message);
} }
/// <summary>
/// Logs a warning message to all registered adapters.
/// </summary>
/// <param name="message">The message to log.</param>
/// <param name="args"></param>
public static void LogWarning(string message, params object[] args)
{
Log(LogLevel.Warning, string.Format(message, args));
}
/// <summary> /// <summary>
/// Logs an error message to all registered adapters. /// Logs an error message to all registered adapters.
/// </summary> /// </summary>
@@ -133,6 +172,16 @@ namespace Telegrator.Logging
Log(LogLevel.Error, message, exception); Log(LogLevel.Error, message, exception);
} }
/// <summary>
/// Logs an error message to all registered adapters.
/// </summary>
/// <param name="message">The message to log.</param>
/// <param name="args"></param>
public static void LogError(string message, params object[] args)
{
Log(LogLevel.Error, string.Format(message, args));
}
/// <summary> /// <summary>
/// Logs an error message with exception only to all registered adapters. /// Logs an error message with exception only to all registered adapters.
/// </summary> /// </summary>
@@ -1,5 +1,6 @@
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegrator.Filters.Components; using Telegrator.Filters.Components;
using Telegrator.Logging;
namespace Telegrator.MadiatorCore.Descriptors namespace Telegrator.MadiatorCore.Descriptors
{ {
@@ -47,7 +48,7 @@ namespace Telegrator.MadiatorCore.Descriptors
{ {
if (!UpdateValidator.CanPass(filterContext)) if (!UpdateValidator.CanPass(filterContext))
{ {
Alligator.FilterWriteLine("(E) UpdateValidator filter of {0} for Update ({1}) didnt pass!", filterContext.Data["handler_name"], filterContext.Update.Id); Alligator.LogDebug("(E) UpdateValidator filter of {0} for Update ({1}) didnt pass!", filterContext.Data["handler_name"], filterContext.Update.Id);
return false; return false;
} }
@@ -59,7 +60,7 @@ namespace Telegrator.MadiatorCore.Descriptors
{ {
if (!StateKeeperValidator.CanPass(filterContext)) if (!StateKeeperValidator.CanPass(filterContext))
{ {
Alligator.FilterWriteLine("(E) StateKeeperValidator filter of {0} for Update ({1}) didnt pass!", filterContext.Data["handler_name"], filterContext.Update.Id); Alligator.LogDebug("(E) StateKeeperValidator filter of {0} for Update ({1}) didnt pass!", filterContext.Data["handler_name"], filterContext.Update.Id);
return false; return false;
} }
@@ -74,7 +75,7 @@ namespace Telegrator.MadiatorCore.Descriptors
if (!filter.CanPass(filterContext)) if (!filter.CanPass(filterContext))
{ {
if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter) if (filter is not AnonymousCompiledFilter && filter is not AnonymousTypeFilter)
Alligator.FilterWriteLine("(E) {0} filter of {1} for Update ({2}) didnt pass!", filter.GetType().Name, filterContext.Data["handler_name"], filterContext.Update.Id); Alligator.LogDebug("(E) {0} filter of {1} for Update ({2}) didnt pass!", filter.GetType().Name, filterContext.Data["handler_name"], filterContext.Update.Id);
return false; return false;
} }
+14 -13
View File
@@ -6,6 +6,7 @@ using Telegram.Bot.Types.Enums;
using Telegrator.Configuration; using Telegrator.Configuration;
using Telegrator.Filters.Components; using Telegrator.Filters.Components;
using Telegrator.Handlers.Components; using Telegrator.Handlers.Components;
using Telegrator.Logging;
using Telegrator.MadiatorCore; using Telegrator.MadiatorCore;
using Telegrator.MadiatorCore.Descriptors; using Telegrator.MadiatorCore.Descriptors;
@@ -84,7 +85,7 @@ namespace Telegrator.Polling
/// <returns>A task representing the asynchronous error handling operation.</returns> /// <returns>A task representing the asynchronous error handling operation.</returns>
public virtual Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, HandleErrorSource source, CancellationToken cancellationToken) public virtual Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, HandleErrorSource source, CancellationToken cancellationToken)
{ {
Alligator.RouterWriteLine("Handling exception {0}", exception.GetType().Name); Alligator.LogDebug("Handling exception {0}", exception.GetType().Name);
ExceptionHandler?.HandleException(botClient, exception, source, cancellationToken); ExceptionHandler?.HandleException(botClient, exception, source, cancellationToken);
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -99,7 +100,7 @@ namespace Telegrator.Polling
public virtual async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) public virtual async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{ {
// Logging // Logging
Alligator.RouterWriteLine("Received Update ({0}) of type \"{1}\"", update.Id, update.Type); Alligator.LogDebug("Received Update ({0}) of type \"{1}\"", update.Id, update.Type);
LogUpdate(update); LogUpdate(update);
try try
@@ -114,22 +115,22 @@ namespace Telegrator.Polling
// Chicking if awaiting handlers has exclusive routing // Chicking if awaiting handlers has exclusive routing
if (Options.ExclusiveAwaitingHandlerRouting) if (Options.ExclusiveAwaitingHandlerRouting)
{ {
Alligator.RouterWriteLine("Receiving Update ({0}) completed with only awaiting handlers", update.Id); Alligator.LogDebug("Receiving Update ({0}) completed with only awaiting handlers", update.Id);
return; return;
} }
} }
// Queuing reagular handlers for execution // Queuing reagular handlers for execution
await HandlersPool.Enqueue(GetHandlers(HandlersProvider, this, botClient, update, cancellationToken)); await HandlersPool.Enqueue(GetHandlers(HandlersProvider, this, botClient, update, cancellationToken));
Alligator.RouterWriteLine("Receiving Update ({0}) finished", update.Id); Alligator.LogDebug("Receiving Update ({0}) finished", update.Id);
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
Alligator.RouterWriteLine("Receiving Update ({0}) cancelled", update.Id); Alligator.LogDebug("Receiving Update ({0}) cancelled", update.Id);
} }
catch (Exception ex) catch (Exception ex)
{ {
Alligator.RouterWriteLine("Receiving Update ({0}) finished with exception {1}", update.Id, ex.Message); Alligator.LogDebug("Receiving Update ({0}) finished with exception {1}", update.Id, ex.Message);
ExceptionHandler?.HandleException(botClient, ex, HandleErrorSource.PollingError, cancellationToken); ExceptionHandler?.HandleException(botClient, ex, HandleErrorSource.PollingError, cancellationToken);
} }
} }
@@ -146,16 +147,16 @@ namespace Telegrator.Polling
/// <returns>A collection of described handler information for the update</returns> /// <returns>A collection of described handler information for the update</returns>
protected virtual IEnumerable<DescribedHandlerInfo> GetHandlers(IHandlersProvider provider, IUpdateRouter updateRouter, ITelegramBotClient client, Update update, CancellationToken cancellationToken = default) protected virtual IEnumerable<DescribedHandlerInfo> GetHandlers(IHandlersProvider provider, IUpdateRouter updateRouter, ITelegramBotClient client, Update update, CancellationToken cancellationToken = default)
{ {
Alligator.RouterWriteLine("Requested handlers for UpdateType.{0}", update.Type); Alligator.LogDebug("Requested handlers for UpdateType.{0}", update.Type);
if (!provider.TryGetDescriptorList(update.Type, out HandlerDescriptorList? descriptors)) if (!provider.TryGetDescriptorList(update.Type, out HandlerDescriptorList? descriptors))
{ {
Alligator.RouterWriteLine("No registered, providing Any"); Alligator.LogDebug("No registered, providing Any");
provider.TryGetDescriptorList(UpdateType.Unknown, out descriptors); provider.TryGetDescriptorList(UpdateType.Unknown, out descriptors);
} }
if (descriptors == null || descriptors.Count == 0) if (descriptors == null || descriptors.Count == 0)
{ {
Alligator.RouterWriteLine("No handlers provided"); Alligator.LogDebug("No handlers provided");
return []; return [];
} }
@@ -181,7 +182,7 @@ namespace Telegrator.Polling
{ {
try try
{ {
Alligator.RouterWriteLine("Describing descriptors of descriptorsList.HandlingType.{0} for Update ({1})", descriptors.HandlingType, update.Id); Alligator.LogDebug("Describing descriptors of descriptorsList.HandlingType.{0} for Update ({1})", descriptors.HandlingType, update.Id);
foreach (HandlerDescriptor descriptor in descriptors.Reverse()) foreach (HandlerDescriptor descriptor in descriptors.Reverse())
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
@@ -199,7 +200,7 @@ namespace Telegrator.Polling
} }
finally finally
{ {
Alligator.RouterWriteLine("Describing for Update ({0}) finished", update.Id); Alligator.LogDebug("Describing for Update ({0}) finished", update.Id);
} }
} }
@@ -253,7 +254,7 @@ namespace Telegrator.Polling
if (msg.Sticker != null) if (msg.Sticker != null)
sb.AppendFormat(" with sticker '{0}'", msg.Sticker.Emoji); sb.AppendFormat(" with sticker '{0}'", msg.Sticker.Emoji);
Alligator.RouterWriteLine(sb.ToString()); Alligator.LogDebug(sb.ToString());
break; break;
} }
@@ -268,7 +269,7 @@ namespace Telegrator.Polling
if (cq.From != null) if (cq.From != null)
sb.AppendFormat(" with data '{0}'", cq.Data); sb.AppendFormat(" with data '{0}'", cq.Data);
Alligator.RouterWriteLine(sb.ToString()); Alligator.LogDebug(sb.ToString());
break; break;
} }
} }
+4 -3
View File
@@ -3,6 +3,7 @@ using System.Runtime.CompilerServices;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using Telegrator.Handlers.Components; using Telegrator.Handlers.Components;
using Telegrator.Logging;
using Telegrator.MadiatorCore; using Telegrator.MadiatorCore;
using Telegrator.MadiatorCore.Descriptors; using Telegrator.MadiatorCore.Descriptors;
@@ -40,7 +41,7 @@ namespace Telegrator.Providers
AllowedTypes = handlers.AllowedTypes; AllowedTypes = handlers.AllowedTypes;
HandlersDictionary = handlers.Values.ForEach(list => list.Freeze()).ToReadOnlyDictionary(list => list.HandlingType); HandlersDictionary = handlers.Values.ForEach(list => list.Freeze()).ToReadOnlyDictionary(list => list.HandlingType);
Options = options ?? throw new ArgumentNullException(nameof(options)); Options = options ?? throw new ArgumentNullException(nameof(options));
Alligator.ProviderWriteLine("{0} created!", GetType().Name); Alligator.LogDebug("{0} created!", GetType().Name);
} }
/// <summary> /// <summary>
@@ -54,7 +55,7 @@ namespace Telegrator.Providers
AllowedTypes = Update.AllTypes; AllowedTypes = Update.AllTypes;
HandlersDictionary = handlers.ForEach(list => list.Freeze()).ToReadOnlyDictionary(list => list.HandlingType); HandlersDictionary = handlers.ForEach(list => list.Freeze()).ToReadOnlyDictionary(list => list.HandlingType);
Options = options ?? throw new ArgumentNullException(nameof(options)); Options = options ?? throw new ArgumentNullException(nameof(options));
Alligator.ProviderWriteLine("{0} created!", GetType().Name); Alligator.LogDebug("{0} created!", GetType().Name);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -78,7 +79,7 @@ namespace Telegrator.Providers
} }
catch catch
{ {
Alligator.ProviderWriteLine("Failed to create instance of {0}", descriptor.ToString()); Alligator.LogDebug("Failed to create instance of {0}", descriptor.ToString());
throw; throw;
} }
} }
+1 -1
View File
@@ -80,7 +80,7 @@ namespace Telegrator
updateRouter = new UpdateRouter(handlerProvider, awaitingProvider, Options, BotInfo); updateRouter = new UpdateRouter(handlerProvider, awaitingProvider, Options, BotInfo);
// Log startup // Log startup
Alligator.LogInformation($"Telegrator bot starting up - BotId: {BotInfo.Id}, Username: {BotInfo.Username}, MaxParallelHandlers: {Options.MaximumParallelWorkingHandlers ?? -1}"); Alligator.LogInformation($"Telegrator bot starting up - BotId: {BotInfo.User.Id}, Username: {BotInfo.User.Username}, MaxParallelHandlers: {Options.MaximumParallelWorkingHandlers ?? -1}");
StartReceivingInternal(receiverOptions, cancellationToken); StartReceivingInternal(receiverOptions, cancellationToken);
} }
-8
View File
@@ -8,14 +8,6 @@ namespace Telegrator
/// </summary> /// </summary>
public class TelegratorOptions : ITelegratorOptions public class TelegratorOptions : ITelegratorOptions
{ {
/*
/// <inheritdoc/>
public bool ExecuteOnlyFirstFoundHanlder { get; set; }
/// <inheritdoc/>
public bool DescendDescriptorIndex { get; set; } = true;
*/
/// <inheritdoc/> /// <inheritdoc/>
public int? MaximumParallelWorkingHandlers { get; set; } public int? MaximumParallelWorkingHandlers { get; set; }