Skip to content

Commit

Permalink
Update logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Plerx2493 committed Oct 15, 2023
1 parent 622115a commit 70f7e21
Show file tree
Hide file tree
Showing 11 changed files with 69 additions and 71 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -42,18 +43,17 @@ public async Task Test(CommandContext ctx, DiscordChannel chnl, int limit)
{
var client = ModularDiscordBot.Services.GetRequiredService<DiscordRestClient>();
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)
{
i++;
}

await ctx.RespondAsync($"Found {i} messages");
await ctx.RespondAsync($"Found {i} messages in {sw.ElapsedMilliseconds}ms");

}
}
1 change: 1 addition & 0 deletions ModularAssistentForDiscordServer/ModularDiscordBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
using Quartz;
using Serilog;


namespace MADS;

public class ModularDiscordBot
Expand Down
2 changes: 2 additions & 0 deletions ModularAssistentForDiscordServer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;

namespace MADS;

Expand All @@ -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
Expand Down
18 changes: 10 additions & 8 deletions ModularAssistentForDiscordServer/Services/DiscordClientService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using ILogger = Serilog.ILogger;

namespace MADS.Services;

Expand All @@ -41,14 +42,16 @@ public class DiscordClientService : IHostedService
public LoggingService Logging;
public SlashCommandsExtension SlashCommands;
public DateTime StartTime;

private static ILogger _logger = Log.ForContext<DiscordClientService>();

public DiscordClientService
(
ConfigJson pConfig,
IDbContextFactory<MadsContext> dbDbContextFactory
)
{
Log.Warning("DiscordClientService");
_logger.Warning("DiscordClientService");

StartTime = DateTime.Now;
var config = pConfig;
Expand Down Expand Up @@ -94,7 +97,7 @@ IDbContextFactory<MadsContext> 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;
Expand Down Expand Up @@ -124,15 +127,14 @@ IDbContextFactory<MadsContext> 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);
}
Expand Down
7 changes: 4 additions & 3 deletions ModularAssistentForDiscordServer/Services/LoggingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
using MADS.Extensions;
using Microsoft.Extensions.Logging;
using Serilog;
using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace MADS.Services;

Expand All @@ -38,6 +39,8 @@ public class LoggingService
private DiscordWebhookClient _discordWebhookClient = new();
private bool _isSetup;
private List<DiscordDmChannel> _ownerChannel = new();

private static Serilog.ILogger _logger = Log.ForContext<LoggingService>();

internal LoggingService(DiscordClientService dBot)
{
Expand All @@ -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
Expand Down Expand Up @@ -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);
}
Expand Down
16 changes: 9 additions & 7 deletions ModularAssistentForDiscordServer/Services/MessageSnipeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -31,6 +31,8 @@ public class MessageSnipeService : IHostedService
private readonly DiscordClientService _discordClientService;
private DiscordClient Discord => _discordClientService.DiscordClient;

private static ILogger _logger = Log.ForContext<MessageSnipeService>();

public MessageSnipeService(IMemoryCache memoryCache, DiscordClientService discordClientService)
{
_memoryCache = memoryCache;
Expand All @@ -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;

Expand All @@ -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;
Expand All @@ -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<MessageSnipeService>().Verbose("MessageSniper: Message eviction - {Reason}", reason.Humanize());
_logger.Verbose("MessageSniper: Message eviction - {Reason}", reason.Humanize());
}

public void AddMessage(DiscordMessage message)
Expand Down
19 changes: 0 additions & 19 deletions ModularAssistentForDiscordServer/Services/ModerationService.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -40,6 +42,8 @@ public class TokenListener : IDisposable, IHostedService
private readonly DiscordClient _client;
private Thread _listenTask;

private static Serilog.ILogger _logger = Log.ForContext<TokenListener>();

public TokenListener(string port, DiscordClient client, string path = "/")
{
_url = $"http://localhost:{port}{path}";
Expand All @@ -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))
{
Expand All @@ -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;
}

Expand Down
11 changes: 7 additions & 4 deletions ModularAssistentForDiscordServer/Services/ReminderService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
using Microsoft.Extensions.Logging;
using Quartz;
using Serilog;
using ILogger = Serilog.ILogger;

namespace MADS.Services;

Expand All @@ -34,6 +35,8 @@ public class ReminderService : IHostedService
private bool _isDisposed;
private bool _isRunning;
private readonly DiscordRestClient _restClient;

private static ILogger _logger = Log.ForContext<ReminderService>();

public ReminderService(IDbContextFactory<MadsContext> dbContextFactory, ISchedulerFactory schedulerFactory,
DiscordClient client, DiscordRestClient rest)
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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);
}
Expand Down
Loading

0 comments on commit 70f7e21

Please sign in to comment.