From 7574d376398f3edf4cdf24fbd7cc8f840085bc73 Mon Sep 17 00:00:00 2001 From: 13xforever Date: Tue, 1 Sep 2020 15:05:27 +0500 Subject: [PATCH] updates for the new logging facilities in the discord client library --- CompatBot/Config.cs | 25 ++++++++++++++++++++----- CompatBot/Program.cs | 36 +----------------------------------- CompatBot/Watchdog.cs | 26 ++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 40 deletions(-) diff --git a/CompatBot/Config.cs b/CompatBot/Config.cs index 81aa3dc2..83b3abcf 100644 --- a/CompatBot/Config.cs +++ b/CompatBot/Config.cs @@ -246,21 +246,36 @@ namespace CompatBot OverflowAction = AsyncTargetWrapperOverflowAction.Block, BatchSize = 500, }; - var logTarget = new ColoredConsoleTarget("logconsole") { + var consoleTarget = new ColoredConsoleTarget("logconsole") { Layout = "${longdate} ${level:uppercase=true:padding=-5} ${message} ${onexception:" + "${newline}${exception:format=Message}" + ":when=not contains('${exception:format=ShortType}','TaskCanceledException')}", }; + var watchdogTarget = new MethodCallTarget("watchdog") + { + ClassName = typeof(Watchdog).AssemblyQualifiedName, + MethodName = nameof(Watchdog.OnLogHandler), + }; + watchdogTarget.Parameters.AddRange(new[] + { + new MethodCallParameter("${level}"), + new MethodCallParameter("${message}"), + }); #if DEBUG - config.AddRule(LogLevel.Trace, LogLevel.Fatal, logTarget, "default"); // only echo messages from default logger to the console + config.AddRule(LogLevel.Trace, LogLevel.Fatal, consoleTarget, "default"); // only echo messages from default logger to the console #else - config.AddRule(LogLevel.Info, LogLevel.Fatal, logTarget, "default"); + config.AddRule(LogLevel.Info, LogLevel.Fatal, consoleTarget, "default"); #endif config.AddRule(LogLevel.Debug, LogLevel.Fatal, asyncFileTarget); + config.AddRule(LogLevel.Info, LogLevel.Fatal, watchdogTarget); - var filter = new ConditionBasedFilter { Condition = "contains('${message}','TaskCanceledException')", Action = FilterResult.Ignore, }; + var ignoreFilter1 = new ConditionBasedFilter { Condition = "contains('${message}','TaskCanceledException')", Action = FilterResult.Ignore, }; + var ignoreFilter2 = new ConditionBasedFilter { Condition = "contains('${message}','One or more pre-execution checks failed')", Action = FilterResult.Ignore, }; foreach (var rule in config.LoggingRules) - rule.Filters.Add(filter); + { + rule.Filters.Add(ignoreFilter1); + rule.Filters.Add(ignoreFilter2); + } LogManager.Configuration = config; return LogManager.GetLogger("default"); } diff --git a/CompatBot/Program.cs b/CompatBot/Program.cs index 4ecdcc12..92b54d00 100644 --- a/CompatBot/Program.cs +++ b/CompatBot/Program.cs @@ -133,6 +133,7 @@ namespace CompatBot Token = Config.Token, TokenType = TokenType.Bot, MessageCacheSize = Config.MessageCacheSize, + LoggerFactory = Config.LoggerFactory, }; using var client = new DiscordClient(config); var commands = client.UseCommandsNext(new CommandsNextConfiguration @@ -265,41 +266,6 @@ namespace CompatBot client.GuildMemberUpdated += UsernameZalgoMonitor.OnMemberUpdated; client.GuildMemberUpdated += UsernameValidationMonitor.OnMemberUpdated; - client.DebugLogger.LogMessageReceived += (sender, eventArgs) => - { - Action logLevel = Config.Log.Info; - if (eventArgs.Level == LogLevel.Debug) - logLevel = Config.Log.Debug; - else if (eventArgs.Level == LogLevel.Info) - { - //logLevel = Config.Log.Info; - if (eventArgs.Message?.Contains("Session resumed") ?? false) - Watchdog.DisconnectTimestamps.Clear(); - } - else if (eventArgs.Level == LogLevel.Warning) - { - logLevel = Config.Log.Warn; - if (eventArgs.Message?.Contains("Dispatch:PRESENCES_REPLACE") ?? false) - BotStatusMonitor.RefreshAsync(client).ConfigureAwait(false).GetAwaiter().GetResult(); - else if (eventArgs.Message?.Contains("Pre-emptive ratelimit triggered") ?? false) - Config.TelemetryClient?.TrackEvent("preemptive-rate-limit"); - } - else if (eventArgs.Level == LogLevel.Error) - { - if (eventArgs.Message?.Contains("DSharpPlus.CommandsNext.Exceptions.ChecksFailedException: One or more pre-execution checks failed.") ?? false) - return; - - logLevel = Config.Log.Error; - } - else if (eventArgs.Level == LogLevel.Critical) - { - logLevel = Config.Log.Fatal; - if ((eventArgs.Message?.Contains("Socket connection terminated") ?? false) - || (eventArgs.Message?.Contains("heartbeats were skipped. Issuing reconnect.") ?? false)) - Watchdog.DisconnectTimestamps.Enqueue(DateTime.UtcNow); - } - logLevel(eventArgs.Exception, eventArgs.Message); - }; Watchdog.DisconnectTimestamps.Enqueue(DateTime.UtcNow); try diff --git a/CompatBot/Watchdog.cs b/CompatBot/Watchdog.cs index fa31b3e2..f884c11c 100644 --- a/CompatBot/Watchdog.cs +++ b/CompatBot/Watchdog.cs @@ -5,8 +5,10 @@ using System.Linq; using System.Threading.Tasks; using CompatBot.Commands; using CompatBot.Database.Providers; +using CompatBot.EventHandlers; using DSharpPlus; using Microsoft.ApplicationInsights; +using NLog; namespace CompatBot { @@ -16,9 +18,11 @@ namespace CompatBot public static readonly ConcurrentQueue DisconnectTimestamps = new ConcurrentQueue(); public static readonly Stopwatch TimeSinceLastIncomingMessage = Stopwatch.StartNew(); private static bool IsOk => DisconnectTimestamps.IsEmpty && TimeSinceLastIncomingMessage.Elapsed < Config.IncomingMessageCheckIntervalInMinutes; + private static DiscordClient discordClient = null; public static async Task Watch(DiscordClient client) { + discordClient = client; do { await Task.Delay(CheckInterval, Config.Cts.Token).ConfigureAwait(false); @@ -62,6 +66,28 @@ namespace CompatBot } while (!Config.Cts.IsCancellationRequested); } + public static void OnLogHandler(string level, string message) + { + if (level == nameof(LogLevel.Info)) + { + if (message?.Contains("Session resumed") ?? false) + DisconnectTimestamps.Clear(); + } + else if (level == nameof(LogLevel.Warn)) + { + if (message?.Contains("Dispatch:PRESENCES_REPLACE") ?? false) + BotStatusMonitor.RefreshAsync(discordClient).ConfigureAwait(false).GetAwaiter().GetResult(); + else if (message?.Contains("Pre-emptive ratelimit triggered") ?? false) + Config.TelemetryClient?.TrackEvent("preemptive-rate-limit"); + } + else if (level == nameof(LogLevel.Fatal)) + { + if ((message?.Contains("Socket connection terminated") ?? false) + || (message?.Contains("heartbeats were skipped. Issuing reconnect.") ?? false)) + DisconnectTimestamps.Enqueue(DateTime.UtcNow); + } + } + public static async Task SendMetrics(DiscordClient client) { do