From 70f7e21d5b7275009f9f9a7f6db0f88386d088d8 Mon Sep 17 00:00:00 2001 From: Plerx <50530305+Plerx2493@users.noreply.github.com> Date: Sun, 15 Oct 2023 19:40:15 +0200 Subject: [PATCH] Update logging --- .../Commands/Text/Base/ExitGuild.cs | 8 ++-- .../ModularDiscordBot.cs | 1 + ModularAssistentForDiscordServer/Program.cs | 2 + .../Services/DiscordClientService.cs | 18 ++++---- .../Services/LoggingService.cs | 7 +-- .../Services/MessageSnipeService.cs | 16 ++++--- .../Services/ModerationService.cs | 19 -------- .../Services/OAuthTokenListenerService.cs | 8 +++- .../Services/ReminderService.cs | 11 +++-- .../Services/StarboardService.cs | 44 +++++++++---------- .../Services/VoiceAlertService.cs | 6 ++- 11 files changed, 69 insertions(+), 71 deletions(-) delete mode 100644 ModularAssistentForDiscordServer/Services/ModerationService.cs diff --git a/ModularAssistentForDiscordServer/Commands/Text/Base/ExitGuild.cs b/ModularAssistentForDiscordServer/Commands/Text/Base/ExitGuild.cs index 36934e9..908765e 100644 --- a/ModularAssistentForDiscordServer/Commands/Text/Base/ExitGuild.cs +++ b/ModularAssistentForDiscordServer/Commands/Text/Base/ExitGuild.cs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System.Diagnostics; using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; @@ -42,10 +43,9 @@ public async Task Test(CommandContext ctx, DiscordChannel chnl, int limit) { var client = ModularDiscordBot.Services.GetRequiredService(); var channel = await client.GetChannelAsync(chnl.Id); - var messages = channel.GetMessagesAfterAsync(ctx.Message.Id + 1221); - - messages.ToBlockingEnumerable().Count(); + var messages = channel.GetMessagesBeforeAsync(ctx.Message.Id + 1221, limit); + var sw = Stopwatch.StartNew(); int i = 0; await foreach (var message in messages) @@ -53,7 +53,7 @@ public async Task Test(CommandContext ctx, DiscordChannel chnl, int limit) i++; } - await ctx.RespondAsync($"Found {i} messages"); + await ctx.RespondAsync($"Found {i} messages in {sw.ElapsedMilliseconds}ms"); } } \ No newline at end of file diff --git a/ModularAssistentForDiscordServer/ModularDiscordBot.cs b/ModularAssistentForDiscordServer/ModularDiscordBot.cs index 8d2bcab..8f05a8e 100644 --- a/ModularAssistentForDiscordServer/ModularDiscordBot.cs +++ b/ModularAssistentForDiscordServer/ModularDiscordBot.cs @@ -22,6 +22,7 @@ using Quartz; using Serilog; + namespace MADS; public class ModularDiscordBot diff --git a/ModularAssistentForDiscordServer/Program.cs b/ModularAssistentForDiscordServer/Program.cs index 7d73203..a73507a 100644 --- a/ModularAssistentForDiscordServer/Program.cs +++ b/ModularAssistentForDiscordServer/Program.cs @@ -23,6 +23,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; +using Serilog.Events; namespace MADS; @@ -32,6 +33,7 @@ public async static Task Main() { Log.Logger = new LoggerConfiguration() .WriteTo.Console() + .MinimumLevel.Override("Quartz", LogEventLevel.Warning) .CreateLogger(); //Create cancellationToken and hook the cancelKey diff --git a/ModularAssistentForDiscordServer/Services/DiscordClientService.cs b/ModularAssistentForDiscordServer/Services/DiscordClientService.cs index eaff538..8ba731d 100644 --- a/ModularAssistentForDiscordServer/Services/DiscordClientService.cs +++ b/ModularAssistentForDiscordServer/Services/DiscordClientService.cs @@ -30,6 +30,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; +using ILogger = Serilog.ILogger; namespace MADS.Services; @@ -41,6 +42,8 @@ public class DiscordClientService : IHostedService public LoggingService Logging; public SlashCommandsExtension SlashCommands; public DateTime StartTime; + + private static ILogger _logger = Log.ForContext(); public DiscordClientService ( @@ -48,7 +51,7 @@ public DiscordClientService IDbContextFactory dbDbContextFactory ) { - Log.Warning("DiscordClientService"); + _logger.Warning("DiscordClientService"); StartTime = DateTime.Now; var config = pConfig; @@ -94,7 +97,7 @@ IDbContextFactory dbDbContextFactory #if RELEASE SlashCommands.RegisterCommands(asm); #else - DiscordClient.Logger.LogWarning("DEBUG"); + _logger.Warning("SlashCommands are registered in debug mode"); SlashCommands.RegisterCommands(asm, 938120155974750288); #endif SlashCommands.SlashCommandErrored += EventListener.OnSlashCommandErrored; @@ -124,15 +127,14 @@ IDbContextFactory dbDbContextFactory public async Task StartAsync(CancellationToken cancellationToken) { - Log.Warning("DiscordClientService started"); - //Update database to latest version - var context = await _dbContextFactory.CreateDbContextAsync(); + _logger.Warning("DiscordClientService started"); + //Update database to latest migration + using var context = await _dbContextFactory.CreateDbContextAsync(); if ((await context.Database.GetPendingMigrationsAsync()).Any()) await context.Database.MigrateAsync(); - DiscordActivity act = new("over some Servers", ActivityType.Watching); - - + DiscordActivity act = new("Messing with code", ActivityType.Custom); + //connect client await DiscordClient.ConnectAsync(act, UserStatus.Online); } diff --git a/ModularAssistentForDiscordServer/Services/LoggingService.cs b/ModularAssistentForDiscordServer/Services/LoggingService.cs index 55f0de3..f36ce4f 100644 --- a/ModularAssistentForDiscordServer/Services/LoggingService.cs +++ b/ModularAssistentForDiscordServer/Services/LoggingService.cs @@ -23,6 +23,7 @@ using MADS.Extensions; using Microsoft.Extensions.Logging; using Serilog; +using ILogger = Microsoft.Extensions.Logging.ILogger; namespace MADS.Services; @@ -38,6 +39,8 @@ public class LoggingService private DiscordWebhookClient _discordWebhookClient = new(); private bool _isSetup; private List _ownerChannel = new(); + + private static Serilog.ILogger _logger = Log.ForContext(); internal LoggingService(DiscordClientService dBot) { @@ -54,8 +57,6 @@ internal LoggingService(DiscordClientService dBot) File.AppendAllText(_logPath, $".Net: {RuntimeInformation.FrameworkDescription}\n", Encoding.UTF8); File.AppendAllText(_logPath, $"Operating system: {os}\n", Encoding.UTF8); File.AppendAllText(_logPath, "========== LOG START ==========\n\n", Encoding.UTF8); - - Console.WriteLine(_logPath); } //Fetching Linux name by Naamloos. Can be found in Naamloos/Modcore @@ -123,7 +124,7 @@ private async void AddOwnerChannels() _ownerChannel.Add(ownerChannel); } - _modularDiscordBot.DiscordClient.Logger.LogInformation( + _logger.Information( "Found {OwnerChannel} dm Channel for {Owner} application owner", _ownerChannel.Count, owners.Length); } diff --git a/ModularAssistentForDiscordServer/Services/MessageSnipeService.cs b/ModularAssistentForDiscordServer/Services/MessageSnipeService.cs index 7b9af28..e68a199 100644 --- a/ModularAssistentForDiscordServer/Services/MessageSnipeService.cs +++ b/ModularAssistentForDiscordServer/Services/MessageSnipeService.cs @@ -19,8 +19,8 @@ using MADS.Extensions; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; using Serilog; +using ILogger = Serilog.ILogger; namespace MADS.Services; @@ -31,6 +31,8 @@ public class MessageSnipeService : IHostedService private readonly DiscordClientService _discordClientService; private DiscordClient Discord => _discordClientService.DiscordClient; + private static ILogger _logger = Log.ForContext(); + public MessageSnipeService(IMemoryCache memoryCache, DiscordClientService discordClientService) { _memoryCache = memoryCache; @@ -43,7 +45,7 @@ public MessageSnipeService(IMemoryCache memoryCache, DiscordClientService discor public Task StartAsync(CancellationToken cancellationToken) { - Log.Warning("Sniper active!"); + _logger.Warning("Sniper active!"); Discord.MessageDeleted += MessageSniperDeleted; Discord.MessageUpdated += MessageSniperEdited; @@ -70,8 +72,8 @@ MessageDeleteEventArgs e if ((!string.IsNullOrEmpty(e.Message?.Content) || e.Message?.Attachments.Count > 0) && !e.Message.Author.IsBot) { AddMessage(e.Message); - Log.Warning("Sniped!"); - sender.Logger.LogTrace("Message added to cache"); + _logger.Warning("Sniped!"); + _logger.Verbose("Message added to cache"); } return Task.CompletedTask; @@ -90,15 +92,15 @@ MessageUpdateEventArgs e || e.Message.Author.IsBot) return Task.CompletedTask; AddEditedMessage(e.MessageBefore); - Log.Warning("Sniped!"); + _logger.Warning("Sniped!"); - sender.Logger.LogTrace("Message edit added to cache"); + _logger.Verbose("Message edit added to cache"); return Task.CompletedTask; } private static void PostEvictionCallback(object key, object value, EvictionReason reason, object state) { - Log.ForContext().Verbose("MessageSniper: Message eviction - {Reason}", reason.Humanize()); + _logger.Verbose("MessageSniper: Message eviction - {Reason}", reason.Humanize()); } public void AddMessage(DiscordMessage message) diff --git a/ModularAssistentForDiscordServer/Services/ModerationService.cs b/ModularAssistentForDiscordServer/Services/ModerationService.cs deleted file mode 100644 index 16a86dd..0000000 --- a/ModularAssistentForDiscordServer/Services/ModerationService.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2023 Plerx2493 -// -// Licensed under the Apache License, Version 2.0 (the "License") -// You may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -namespace MADS.Services; - -internal class ModerationService -{ -} \ No newline at end of file diff --git a/ModularAssistentForDiscordServer/Services/OAuthTokenListenerService.cs b/ModularAssistentForDiscordServer/Services/OAuthTokenListenerService.cs index e71995f..9a66b06 100644 --- a/ModularAssistentForDiscordServer/Services/OAuthTokenListenerService.cs +++ b/ModularAssistentForDiscordServer/Services/OAuthTokenListenerService.cs @@ -17,6 +17,8 @@ using DSharpPlus; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using Serilog; +using ILogger = Microsoft.Extensions.Logging.ILogger; namespace MADS.Services; @@ -40,6 +42,8 @@ public class TokenListener : IDisposable, IHostedService private readonly DiscordClient _client; private Thread _listenTask; + private static Serilog.ILogger _logger = Log.ForContext(); + public TokenListener(string port, DiscordClient client, string path = "/") { _url = $"http://localhost:{port}{path}"; @@ -56,7 +60,7 @@ public void Dispose() public Task StartAsync(CancellationToken cancellationToken) { _listener.Start(); - _client.Logger.LogInformation("Listening for connections on {Url}", _url); + _logger.Information("Listening for connections on {Url}", _url); _listenTask = new Thread(() => _ = HandleIncomingConnections(cancellationToken)) { @@ -72,7 +76,7 @@ public Task StopAsync(CancellationToken cancellationToken) { _listener.Abort(); _listenTask.Interrupt(); - _client.Logger.LogInformation("Tokenlistener stopped"); + _logger.Information("Tokenlistener stopped"); return Task.CompletedTask; } diff --git a/ModularAssistentForDiscordServer/Services/ReminderService.cs b/ModularAssistentForDiscordServer/Services/ReminderService.cs index 62fbaea..b7cba79 100644 --- a/ModularAssistentForDiscordServer/Services/ReminderService.cs +++ b/ModularAssistentForDiscordServer/Services/ReminderService.cs @@ -22,6 +22,7 @@ using Microsoft.Extensions.Logging; using Quartz; using Serilog; +using ILogger = Serilog.ILogger; namespace MADS.Services; @@ -34,6 +35,8 @@ public class ReminderService : IHostedService private bool _isDisposed; private bool _isRunning; private readonly DiscordRestClient _restClient; + + private static ILogger _logger = Log.ForContext(); public ReminderService(IDbContextFactory dbContextFactory, ISchedulerFactory schedulerFactory, DiscordClient client, DiscordRestClient rest) @@ -55,7 +58,7 @@ public async Task StartAsync(CancellationToken cancellationToken) if (ReminderScheduler == null) throw new NullReferenceException(); await ReminderScheduler.Start(); _isRunning = true; - _client.Logger.LogInformation("Reminders active"); + _logger.Information("Reminders active"); } public async Task StopAsync(CancellationToken cancellationToken) @@ -65,7 +68,7 @@ public async Task StopAsync(CancellationToken cancellationToken) _isDisposed = true; _isRunning = false; await ReminderScheduler.Shutdown(); - _client.Logger.LogInformation("Reminders stopped"); + _logger.Information("Reminders stopped"); } private async Task DispatchReminder(ReminderDbEntity reminder) @@ -165,12 +168,12 @@ public async Task Execute(IJobExecutionContext context) if (reminder is null) { - Log.Warning("Tried to dispatch a nonexistent reminder: {Id} ", + _logger.Warning("Tried to dispatch a nonexistent reminder: {Id} ", Convert.ToUInt64(dataMap.Get("reminderId"))); return; } - Log.Information("Dispatching reminder id: {Id}", reminder.Id); + _logger.Information("Dispatching reminder id: {Id}", reminder.Id); await _reminder.DispatchReminder(reminder); } diff --git a/ModularAssistentForDiscordServer/Services/StarboardService.cs b/ModularAssistentForDiscordServer/Services/StarboardService.cs index 6be66bc..7414828 100644 --- a/ModularAssistentForDiscordServer/Services/StarboardService.cs +++ b/ModularAssistentForDiscordServer/Services/StarboardService.cs @@ -21,7 +21,8 @@ using MADS.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; +using Serilog; +using ILogger = Serilog.ILogger; namespace MADS.Services; @@ -32,10 +33,12 @@ public class StarboardService : IHostedService private readonly BlockingCollection _messageQueue; private bool _stopped; + private static ILogger _logger = Log.ForContext(); + public StarboardService(DiscordClientService client, IDbContextFactory dbFactory) { _client = client.DiscordClient; - _messageQueue = new(); + _messageQueue = new BlockingCollection(); _dbFactory = dbFactory; } @@ -46,7 +49,7 @@ public Task StartAsync(CancellationToken cancellationToken) _client.MessageReactionsCleared += HandleReactionsCleared; _client.MessageReactionRemovedEmoji += HandleReactionEmojiRemoved; StartHandleQueue(); - _client.Logger.LogInformation("Starboard active"); + _logger.Information("Starboard active"); return Task.CompletedTask; } @@ -57,7 +60,7 @@ public Task StopAsync(CancellationToken cancellationToken) _client.MessageReactionsCleared -= HandleReactionsCleared; _client.MessageReactionRemovedEmoji -= HandleReactionEmojiRemoved; _stopped = true; - _client.Logger.LogInformation("Starboard stopped"); + _logger.Information("Starboard stopped"); return Task.CompletedTask; } @@ -117,15 +120,14 @@ private void StartHandleQueue() { try { - ModularDiscordBot.Logger.LogTrace("StarboardService: waiting for message"); + _logger.Verbose("StarboardService: waiting for message"); var msg = _messageQueue.Take(); - ModularDiscordBot.Logger.LogTrace("StarboardService: message received"); + _logger.Verbose("StarboardService: message received"); await HandleEvent(msg); } catch (Exception e) { - ModularDiscordBot.Logger.LogError($"{nameof(StarboardService)}: " + e.Message + "\n" + - e.StackTrace); + _logger.Error("Exception in {Source}: {Message}", nameof(StarboardService), e.Message); } } }); @@ -140,8 +142,7 @@ private async Task HandleEvent(DiscordReactionUpdateEvent e) var eventArgs = (MessageReactionAddEventArgs) e.EventArgs; if (eventArgs.User.IsBot) return; } - - + using MadsContext db = await _dbFactory.CreateDbContextAsync(); var guildSettings = db.Configs.FirstOrDefault(x => x.DiscordGuildId == e.Message.Channel.GuildId); @@ -153,7 +154,7 @@ private async Task HandleEvent(DiscordReactionUpdateEvent e) || guildSettings.StarboardThreshold == null || guildSettings.StarboardChannelId == null) { - _client.Logger.LogError("GuildSettings incomplete: StarboardSettings"); + _logger.Error("GuildSettings incomplete: StarboardSettings"); return; } @@ -195,24 +196,23 @@ private async Task HandleEvent(DiscordReactionUpdateEvent e) return; case DiscordReactionUpdateType.ReactionEmojiRemoved: - var argss = (MessageReactionRemoveEmojiEventArgs) e.EventArgs; + var args = (MessageReactionRemoveEmojiEventArgs) e.EventArgs; if (guildSettings.StarboardEmojiId != 0) discordEmoji = DiscordEmoji.FromGuildEmote(_client, guildSettings.StarboardEmojiId.Value); else discordEmoji = DiscordEmoji.FromUnicode(_client, guildSettings.StarboardEmojiName!); - if (argss.Emoji != discordEmoji) return; - var msgss = db.Starboard.Where(x => + if (args.Emoji != discordEmoji) return; + var messages = db.Starboard.Where(x => x.DiscordMessageId == e.Message.Id && x.DiscordChannelId == e.Message.ChannelId); - db.Starboard.RemoveRange(msgss); + db.Starboard.RemoveRange(messages); return; default: throw new ArgumentOutOfRangeException(); } - - + StarboardMessageDbEntity? starData; var isNew = false; starData = db.Starboard.FirstOrDefault(x => @@ -275,7 +275,7 @@ private async Task DeleteStarboardMessage(StarboardMessageDbEntity starData) } catch (Exception) { - ModularDiscordBot.Logger.LogError("StarboardMessage not found"); + _logger.Error("{Source}: Message with id {Id} not found", nameof(StarboardService), starData.DiscordMessageId); return; } @@ -308,7 +308,7 @@ private async Task UpdateStarboardMessage(StarboardMessageDbEntity starData, Dis } catch (Exception) { - ModularDiscordBot.Logger.LogError("StarboardMessage not found"); + _logger.Error("{Source}: Message with id {Id} not found", nameof(StarboardService), starData.DiscordMessageId); return; } @@ -318,13 +318,13 @@ private async Task UpdateStarboardMessage(StarboardMessageDbEntity starData, Dis private async Task CreateStarboardMessage ( StarboardMessageDbEntity starData, - GuildConfigDbEntity congfig, + GuildConfigDbEntity config, DiscordEmoji emoji ) { var starboardMessageBuilder = await BuildStarboardMessage(starData, emoji); - var starboardChannel = await _client.GetChannelAsync(congfig.StarboardChannelId!.Value); + var starboardChannel = await _client.GetChannelAsync(config.StarboardChannelId!.Value); var starboardMessage = await starboardChannel.SendMessageAsync(starboardMessageBuilder); @@ -359,7 +359,7 @@ DiscordEmoji emoji } catch (Exception) { - ModularDiscordBot.Logger.LogError("StarboardMessage not found"); + _logger.Error("{Source}: Message with id {Id} not found", nameof(StarboardService), starData.DiscordMessageId); throw; } diff --git a/ModularAssistentForDiscordServer/Services/VoiceAlertService.cs b/ModularAssistentForDiscordServer/Services/VoiceAlertService.cs index d08b355..236d92e 100644 --- a/ModularAssistentForDiscordServer/Services/VoiceAlertService.cs +++ b/ModularAssistentForDiscordServer/Services/VoiceAlertService.cs @@ -29,6 +29,8 @@ public class VoiceAlertService : IHostedService private readonly IDbContextFactory _contextFactory; private readonly DiscordClient _discordClient; + private static ILogger _logger = Log.ForContext(); + public VoiceAlertService(IDbContextFactory contextFactory, DiscordClientService discordClientService) { _discordClient = discordClientService.DiscordClient; @@ -86,7 +88,7 @@ public async Task HandleEvent(DiscordClient client, VoiceStateUpdateEventArgs e) } catch (DiscordException exception) { - Log.Error(exception, "Failed to send voice alert to {UserId}", alert.UserId); + _logger.Error(exception, "Failed to send voice alert to {UserId}", alert.UserId); } } @@ -122,7 +124,7 @@ public async Task HandleEvent(DiscordClient client, VoiceStateUpdateEventArgs e) alert.MinTimeBetweenAlerts = minTimeBetweenAlerts; } - Log.Information("Voicealert added"); + _logger.Information("Voicealert added"); await context.VoiceAlerts.AddAsync(alert); await context.SaveChangesAsync();