Skip to content
This repository has been archived by the owner on Jul 14, 2024. It is now read-only.

Commit

Permalink
Remove hidden NLog dependencies
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
oliverbooth committed Mar 26, 2023
1 parent d0826c2 commit e2960a6
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 37 deletions.
37 changes: 18 additions & 19 deletions Cloak/Services/BotService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -16,19 +15,20 @@ namespace Cloak.Services;
/// </summary>
internal sealed class BotService : BackgroundService
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

private readonly IServiceProvider _serviceProvider;
private readonly ILogger<BotService> _logger;
private readonly DiscordClient _discordClient;

/// <summary>
/// Initializes a new instance of the <see cref="BotService" /> class.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
/// <param name="logger">The logger.</param>
/// <param name="discordClient">The Discord client.</param>
public BotService(IServiceProvider serviceProvider, DiscordClient discordClient)
public BotService(IServiceProvider serviceProvider, ILogger<BotService> logger, DiscordClient discordClient)
{
_serviceProvider = serviceProvider;
_logger = logger;
_discordClient = discordClient;

var attribute = typeof(BotService).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
Expand Down Expand Up @@ -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<RoleInfoCommand>();
slashCommands.RegisterCommands<InfoCommand>();
slashCommands.RegisterCommands<RoleCommand>();
slashCommands.RegisterCommands<PersistentRoleCommand>();
slashCommands.RegisterCommands<SelfRoleCommand>();

Logger.Info("Connecting to Discord...");
_logger.LogInformation("Connecting to Discord");
_discordClient.Ready += OnReady;

RegisterEvents(slashCommands);
Expand All @@ -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;
};
Expand All @@ -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;
};

Expand All @@ -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;
};
Expand All @@ -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;
};
Expand All @@ -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;
};
Expand Down
2 changes: 0 additions & 2 deletions Cloak/Services/MemberRoleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
15 changes: 9 additions & 6 deletions Cloak/Services/MemberWatchdogService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using Humanizer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog;
using Microsoft.Extensions.Logging;

namespace Cloak.Services;

Expand All @@ -14,23 +14,26 @@ namespace Cloak.Services;
/// </summary>
internal sealed class MemberWatchdogService : BackgroundService
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private readonly ILogger<MemberWatchdogService> _logger;
private readonly IServiceScopeFactory _scopeFactory;
private readonly DiscordClient _discordClient;
private readonly MemberRoleService _memberRoleService;

/// <summary>
/// Initializes a new instance of the <see cref="MemberWatchdogService" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="scopeFactory">The scope factory.</param>
/// <param name="discordClient">The Discord client.</param>
/// <param name="memberRoleService">The member role service.</param>
public MemberWatchdogService(
ILogger<MemberWatchdogService> logger,
IServiceScopeFactory scopeFactory,
DiscordClient discordClient,
MemberRoleService memberRoleService
)
{
_logger = logger;
_scopeFactory = scopeFactory;
_discordClient = discordClient;
_memberRoleService = memberRoleService;
Expand All @@ -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);
}
}

Expand All @@ -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);
}
}
}
10 changes: 6 additions & 4 deletions Cloak/Services/PersistentRoleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NLog;
using Microsoft.Extensions.Logging;

namespace Cloak.Services;

Expand All @@ -15,18 +15,20 @@ namespace Cloak.Services;
/// </summary>
internal sealed class PersistentRoleService : BackgroundService
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private readonly ILogger<PersistentRoleService> _logger;
private readonly IServiceScopeFactory _scopeFactory;
private readonly DiscordClient _discordClient;
private readonly Dictionary<DiscordGuild, HashSet<DiscordRole>> _persistentRoles = new();

/// <summary>
/// Initializes a new instance of the <see cref="PersistentRoleService" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="scopeFactory">The scope factory.</param>
/// <param name="discordClient">The Discord client.</param>
public PersistentRoleService(IServiceScopeFactory scopeFactory, DiscordClient discordClient)
public PersistentRoleService(ILogger<PersistentRoleService> logger, IServiceScopeFactory scopeFactory, DiscordClient discordClient)
{
_logger = logger;
_scopeFactory = scopeFactory;
_discordClient = discordClient;
}
Expand Down Expand Up @@ -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));
}
}

Expand Down
14 changes: 8 additions & 6 deletions Cloak/Services/SelfRoleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -15,18 +15,20 @@ namespace Cloak.Services;
/// </summary>
internal sealed class SelfRoleService : BackgroundService
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private readonly ILogger<SelfRoleService> _logger;
private readonly IServiceScopeFactory _scopeFactory;
private readonly DiscordClient _discordClient;
private readonly Dictionary<DiscordGuild, Dictionary<SelfRole, DiscordRole>> _selfRoles = new();

/// <summary>
/// Initializes a new instance of the <see cref="SelfRoleService" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="scopeFactory">The service scope factory.</param>
/// <param name="discordClient">The Discord client.</param>
public SelfRoleService(IServiceScopeFactory scopeFactory, DiscordClient discordClient)
public SelfRoleService(ILogger<SelfRoleService> logger, IServiceScopeFactory scopeFactory, DiscordClient discordClient)
{
_logger = logger;
_scopeFactory = scopeFactory;
_discordClient = discordClient;
}
Expand Down Expand Up @@ -58,7 +60,7 @@ public async Task<SelfRole> AddSelfRoleAsync(DiscordGuild guild, DiscordRole rol

selfRoles[selfRole] = role;

Logger.Info($"Added self role {role} to group {group ?? "<none>"}");
_logger.LogInformation("Added self role {Role} to group {Group}", role, group ?? "<none>");
return selfRole;
}

Expand All @@ -80,7 +82,7 @@ public async Task<SelfRole> AddSelfRoleAsync(DiscordGuild guild, DiscordRole rol
context.Update(selfRole);
await context.SaveChangesAsync().ConfigureAwait(false);

Logger.Info($"Edited self role {role} with new group {group ?? "<none>"}");
_logger.LogInformation("Edited self role {Role} with new group {Group}", role, group ?? "<none>");
return selfRole;
}

Expand Down Expand Up @@ -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);
}

/// <summary>
Expand Down

0 comments on commit e2960a6

Please sign in to comment.