From e2960a6e65186b0bf86ee6909b94f46bdb7617cd Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sun, 26 Mar 2023 23:55:06 +0100 Subject: [PATCH] Remove hidden NLog dependencies Loggers for each service type were static in the class, rather than injected by Microsoft.Extensions DI framework. An ILogger is now injected where necessary. This has the added benefit of being future-proof should the project require migration to another logging service such as Serilog (or any other), in the event that NLog is discontinued. --- Cloak/Services/BotService.cs | 37 ++++++++++++------------- Cloak/Services/MemberRoleService.cs | 2 -- Cloak/Services/MemberWatchdogService.cs | 15 ++++++---- Cloak/Services/PersistentRoleService.cs | 10 ++++--- Cloak/Services/SelfRoleService.cs | 14 ++++++---- 5 files changed, 41 insertions(+), 37 deletions(-) diff --git a/Cloak/Services/BotService.cs b/Cloak/Services/BotService.cs index ce46d2d..96c75db 100644 --- a/Cloak/Services/BotService.cs +++ b/Cloak/Services/BotService.cs @@ -6,8 +6,7 @@ using DSharpPlus.Exceptions; using DSharpPlus.SlashCommands; using Microsoft.Extensions.Hosting; -using NLog; -using ILogger = NLog.ILogger; +using Microsoft.Extensions.Logging; namespace Cloak.Services; @@ -16,19 +15,20 @@ namespace Cloak.Services; /// internal sealed class BotService : BackgroundService { - private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); - private readonly IServiceProvider _serviceProvider; + private readonly ILogger _logger; private readonly DiscordClient _discordClient; /// /// Initializes a new instance of the class. /// /// The service provider. + /// The logger. /// The Discord client. - public BotService(IServiceProvider serviceProvider, DiscordClient discordClient) + public BotService(IServiceProvider serviceProvider, ILogger logger, DiscordClient discordClient) { _serviceProvider = serviceProvider; + _logger = logger; _discordClient = discordClient; var attribute = typeof(BotService).Assembly.GetCustomAttribute(); @@ -57,21 +57,21 @@ public override Task StopAsync(CancellationToken cancellationToken) protected override async Task ExecuteAsync(CancellationToken stoppingToken) { StartedAt = DateTimeOffset.UtcNow; - Logger.Info($"Cloak v{Version} is starting..."); + _logger.LogInformation("Cloak v{Version} is starting", Version); SlashCommandsExtension slashCommands = _discordClient.UseSlashCommands(new SlashCommandsConfiguration { Services = _serviceProvider }); - Logger.Info("Registering commands..."); + _logger.LogInformation("Registering commands"); slashCommands.RegisterCommands(); slashCommands.RegisterCommands(); slashCommands.RegisterCommands(); slashCommands.RegisterCommands(); slashCommands.RegisterCommands(); - Logger.Info("Connecting to Discord..."); + _logger.LogInformation("Connecting to Discord"); _discordClient.Ready += OnReady; RegisterEvents(slashCommands); @@ -81,17 +81,17 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) private Task OnReady(DiscordClient sender, ReadyEventArgs e) { - Logger.Info("Discord client ready"); + _logger.LogInformation("Discord client ready"); return Task.CompletedTask; } - private static void RegisterEvents(SlashCommandsExtension slashCommands) + private void RegisterEvents(SlashCommandsExtension slashCommands) { slashCommands.AutocompleteErrored += (_, args) => { - Logger.Error(args.Exception, "An exception was thrown when performing autocomplete"); + _logger.LogError(args.Exception, "An exception was thrown when performing autocomplete"); if (args.Exception is DiscordException discordException) - Logger.Error($"API response: {discordException.JsonMessage}"); + _logger.LogError("API response: {Response}", discordException.JsonMessage); return Task.CompletedTask; }; @@ -102,7 +102,7 @@ private static void RegisterEvents(SlashCommandsExtension slashCommands) if (args.Context.Interaction?.Data?.Options is { } options) optionsString = $" {string.Join(" ", options.Select(o => $"{o?.Name}: '{o?.Value}'"))}"; - Logger.Info($"{args.Context.User} ran slash command /{args.Context.CommandName}{optionsString}"); + _logger.LogInformation("{User} ran slash command /{CommandName}{OptionsString}", args.Context.User, args.Context.CommandName, optionsString); return Task.CompletedTask; }; @@ -123,8 +123,7 @@ private static void RegisterEvents(SlashCommandsExtension slashCommands) if (resolved?.Users?.Count > 0) properties.Add($"users: {string.Join(", ", resolved.Users.Select(r => r.Value.Id))}"); - Logger.Info($"{args.Context.User} invoked context menu '{args.Context.CommandName}' with resolved " + - string.Join("; ", properties)); + _logger.LogInformation("{User} invoked context menu '{Command}' with resolved {Properties}", args.Context.User, args.Context.CommandName, string.Join("; ", properties)); return Task.CompletedTask; }; @@ -139,9 +138,9 @@ private static void RegisterEvents(SlashCommandsExtension slashCommands) } string? name = context.Interaction.Data.Name; - Logger.Error(args.Exception, $"An exception was thrown when executing context menu '{name}'"); + _logger.LogError(args.Exception, "An exception was thrown when executing context menu '{Name}'", name); if (args.Exception is DiscordException discordException) - Logger.Error($"API response: {discordException.JsonMessage}"); + _logger.LogError("API response: {Response}", discordException.JsonMessage); return Task.CompletedTask; }; @@ -156,9 +155,9 @@ private static void RegisterEvents(SlashCommandsExtension slashCommands) } string? name = context.Interaction.Data.Name; - Logger.Error(args.Exception, $"An exception was thrown when executing slash command '{name}'"); + _logger.LogError(args.Exception, "An exception was thrown when executing slash command '{Name}'", name); if (args.Exception is DiscordException discordException) - Logger.Error($"API response: {discordException.JsonMessage}"); + _logger.LogError("API response: {Response}", discordException.JsonMessage); return Task.CompletedTask; }; diff --git a/Cloak/Services/MemberRoleService.cs b/Cloak/Services/MemberRoleService.cs index 4c54a9c..dc59ee5 100644 --- a/Cloak/Services/MemberRoleService.cs +++ b/Cloak/Services/MemberRoleService.cs @@ -5,13 +5,11 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using NLog; namespace Cloak.Services; internal sealed class MemberRoleService : BackgroundService { - private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); private readonly IServiceScopeFactory _scopeFactory; private readonly DiscordClient _discordClient; private readonly PersistentRoleService _persistentRoleService; diff --git a/Cloak/Services/MemberWatchdogService.cs b/Cloak/Services/MemberWatchdogService.cs index ec6ec29..1da64f2 100644 --- a/Cloak/Services/MemberWatchdogService.cs +++ b/Cloak/Services/MemberWatchdogService.cs @@ -5,7 +5,7 @@ using Humanizer; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using NLog; +using Microsoft.Extensions.Logging; namespace Cloak.Services; @@ -14,7 +14,7 @@ namespace Cloak.Services; /// internal sealed class MemberWatchdogService : BackgroundService { - private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); + private readonly ILogger _logger; private readonly IServiceScopeFactory _scopeFactory; private readonly DiscordClient _discordClient; private readonly MemberRoleService _memberRoleService; @@ -22,15 +22,18 @@ internal sealed class MemberWatchdogService : BackgroundService /// /// Initializes a new instance of the class. /// + /// The logger. /// The scope factory. /// The Discord client. /// The member role service. public MemberWatchdogService( + ILogger logger, IServiceScopeFactory scopeFactory, DiscordClient discordClient, MemberRoleService memberRoleService ) { + _logger = logger; _scopeFactory = scopeFactory; _discordClient = discordClient; _memberRoleService = memberRoleService; @@ -54,13 +57,13 @@ private async Task DiscordClientOnGuildMemberAdded(DiscordClient sender, GuildMe { int count = await _memberRoleService.ApplyPersistentRolesAsync(member).ConfigureAwait(false); if (count > 0) - Logger.Info($"Restored {"persistent role".ToQuantity(count)} for {member}"); + _logger.LogInformation("Restored {Quantity} for {Member}", "persistent role".ToQuantity(count), member); await _memberRoleService.RemoveFromDatabaseAsync(member.Guild, member).ConfigureAwait(false); } catch (Exception exception) { - Logger.Error(exception, $"Could not restore persistent roles for {member}"); + _logger.LogError(exception, "Could not restore persistent roles for {Member}", member); } } @@ -71,11 +74,11 @@ private async Task DiscordClientOnGuildMemberRemoved(DiscordClient sender, Guild { int count = await _memberRoleService.SavePersistentRolesAsync(member).ConfigureAwait(false); if (count > 0) - Logger.Info($"Saved {"persistent role".ToQuantity(count)} for {member}"); + _logger.LogInformation("Saved {Quantity} for {Member}", "persistent role".ToQuantity(count), member); } catch (Exception exception) { - Logger.Error(exception, $"Could not save persistent roles for {member}"); + _logger.LogError(exception, "Could not save persistent roles for {Member}", member); } } } diff --git a/Cloak/Services/PersistentRoleService.cs b/Cloak/Services/PersistentRoleService.cs index a5103b1..381e68b 100644 --- a/Cloak/Services/PersistentRoleService.cs +++ b/Cloak/Services/PersistentRoleService.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using NLog; +using Microsoft.Extensions.Logging; namespace Cloak.Services; @@ -15,7 +15,7 @@ namespace Cloak.Services; /// internal sealed class PersistentRoleService : BackgroundService { - private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); + private readonly ILogger _logger; private readonly IServiceScopeFactory _scopeFactory; private readonly DiscordClient _discordClient; private readonly Dictionary> _persistentRoles = new(); @@ -23,10 +23,12 @@ internal sealed class PersistentRoleService : BackgroundService /// /// Initializes a new instance of the class. /// + /// The logger. /// The scope factory. /// The Discord client. - public PersistentRoleService(IServiceScopeFactory scopeFactory, DiscordClient discordClient) + public PersistentRoleService(ILogger logger, IServiceScopeFactory scopeFactory, DiscordClient discordClient) { + _logger = logger; _scopeFactory = scopeFactory; _discordClient = discordClient; } @@ -167,7 +169,7 @@ public async Task RemoveStaleRolesAsync(DiscordGuild guild) context.RemoveRange(rolesToRemove); await context.SaveChangesAsync().ConfigureAwait(false); - Logger.Info($"Removed {"roles".ToQuantity(rolesToRemove.Count)} from the database that mapped to invalid roles"); + _logger.LogInformation("Removed {Quantity} from the database that mapped to invalid roles", "roles".ToQuantity(rolesToRemove.Count)); } } diff --git a/Cloak/Services/SelfRoleService.cs b/Cloak/Services/SelfRoleService.cs index 4a315f1..6bf5f84 100644 --- a/Cloak/Services/SelfRoleService.cs +++ b/Cloak/Services/SelfRoleService.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using NLog; +using Microsoft.Extensions.Logging; namespace Cloak.Services; @@ -15,7 +15,7 @@ namespace Cloak.Services; /// internal sealed class SelfRoleService : BackgroundService { - private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); + private readonly ILogger _logger; private readonly IServiceScopeFactory _scopeFactory; private readonly DiscordClient _discordClient; private readonly Dictionary> _selfRoles = new(); @@ -23,10 +23,12 @@ internal sealed class SelfRoleService : BackgroundService /// /// Initializes a new instance of the class. /// + /// The logger. /// The service scope factory. /// The Discord client. - public SelfRoleService(IServiceScopeFactory scopeFactory, DiscordClient discordClient) + public SelfRoleService(ILogger logger, IServiceScopeFactory scopeFactory, DiscordClient discordClient) { + _logger = logger; _scopeFactory = scopeFactory; _discordClient = discordClient; } @@ -58,7 +60,7 @@ public async Task AddSelfRoleAsync(DiscordGuild guild, DiscordRole rol selfRoles[selfRole] = role; - Logger.Info($"Added self role {role} to group {group ?? ""}"); + _logger.LogInformation("Added self role {Role} to group {Group}", role, group ?? ""); return selfRole; } @@ -80,7 +82,7 @@ public async Task AddSelfRoleAsync(DiscordGuild guild, DiscordRole rol context.Update(selfRole); await context.SaveChangesAsync().ConfigureAwait(false); - Logger.Info($"Edited self role {role} with new group {group ?? ""}"); + _logger.LogInformation("Edited self role {Role} with new group {Group}", role, group ?? ""); return selfRole; } @@ -210,7 +212,7 @@ public async Task RemoveSelfRoleAsync(DiscordGuild guild, DiscordRole role) context.Remove(selfRole); await context.SaveChangesAsync().ConfigureAwait(false); - Logger.Info($"Removed self role {role}"); + _logger.LogInformation("Removed self role {Role}", role); } ///