updates for the new logging facilities in the discord client library

This commit is contained in:
13xforever 2020-09-01 15:05:27 +05:00
parent 94ab23a1d9
commit 7574d37639
3 changed files with 47 additions and 40 deletions

View File

@ -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");
}

View File

@ -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<Exception, string> 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

View File

@ -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<DateTime> DisconnectTimestamps = new ConcurrentQueue<DateTime>();
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