- Added serilog analyzer which will help with fully moving to structured logging

- Small code cleanups
This commit is contained in:
Kwoth
2022-01-03 13:38:19 +01:00
parent ade880a6e6
commit ef49030841
4 changed files with 38 additions and 32 deletions

View File

@@ -2,7 +2,7 @@
using System.Security.Cryptography; using System.Security.Cryptography;
namespace NadekoBot.Common; namespace NadekoBot.Common;
// todo minby maxby
public class NadekoRandom : Random public class NadekoRandom : Random
{ {
private readonly RandomNumberGenerator _rng; private readonly RandomNumberGenerator _rng;

View File

@@ -64,7 +64,6 @@ public partial class Gambling : GamblingModule<GamblingService>
{ {
var flowersCi = (CultureInfo)Culture.Clone(); var flowersCi = (CultureInfo)Culture.Clone();
flowersCi.NumberFormat.CurrencySymbol = CurrencySign; flowersCi.NumberFormat.CurrencySymbol = CurrencySign;
Log.Information(string.Join(",", flowersCi.NumberFormat.NativeDigits));
return cur.ToString("C0", flowersCi); return cur.ToString("C0", flowersCi);
} }
@@ -109,10 +108,9 @@ public partial class Gambling : GamblingModule<GamblingService>
return; return;
} }
TimeSpan? rem; if (_cache.AddTimelyClaim(ctx.User.Id, period) is { } rem)
if ((rem = _cache.AddTimelyClaim(ctx.User.Id, period)) is not null)
{ {
await ReplyErrorLocalizedAsync(strs.timely_already_claimed(rem?.ToString(@"dd\d\ hh\h\ mm\m\ ss\s"))); await ReplyErrorLocalizedAsync(strs.timely_already_claimed(rem.ToString(@"dd\d\ hh\h\ mm\m\ ss\s")));
return; return;
} }
@@ -240,7 +238,7 @@ public partial class Gambling : GamblingModule<GamblingService>
[Cmd] [Cmd]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
[Priority(0)] [Priority(0)]
public async partial Task Give(ShmartNumber amount, IGuildUser receiver, [Leftover] string msg = null) public async partial Task Give(ShmartNumber amount, IGuildUser receiver, [Leftover] string msg)
{ {
if (amount <= 0 || ctx.User.Id == receiver.Id || receiver.IsBot) if (amount <= 0 || ctx.User.Id == receiver.Id || receiver.IsBot)
return; return;
@@ -409,15 +407,15 @@ public partial class Gambling : GamblingModule<GamblingService>
if (_service.Duels.TryAdd((u.Id, ctx.User.Id), game)) if (_service.Duels.TryAdd((u.Id, ctx.User.Id), game))
{ {
game.OnGameTick += Game_OnGameTick; game.OnGameTick += GameOnGameTick;
game.OnEnded += Game_OnEnded; game.OnEnded += GameOnEnded;
await ReplyConfirmLocalizedAsync(strs.roll_duel_challenge(Format.Bold(ctx.User.ToString()), await ReplyConfirmLocalizedAsync(strs.roll_duel_challenge(Format.Bold(ctx.User.ToString()),
Format.Bold(u.ToString()), Format.Bold(u.ToString()),
Format.Bold(n(amount)))); Format.Bold(n(amount))));
} }
async Task Game_OnGameTick(RollDuelGame arg) async Task GameOnGameTick(RollDuelGame arg)
{ {
var rolls = arg.Rolls.Last(); var rolls = arg.Rolls.Last();
description += $@"{Format.Bold(ctx.User.ToString())} rolled **{rolls.Item1}** description += $@"{Format.Bold(ctx.User.ToString())} rolled **{rolls.Item1}**
@@ -435,7 +433,7 @@ public partial class Gambling : GamblingModule<GamblingService>
}); });
} }
async Task Game_OnEnded(RollDuelGame rdGame, RollDuelGame.Reason reason) async Task GameOnEnded(RollDuelGame rdGame, RollDuelGame.Reason reason)
{ {
try try
{ {
@@ -515,14 +513,13 @@ public partial class Gambling : GamblingModule<GamblingService>
var (opts, _) = OptionsParser.ParseFrom(new LbOpts(), args); var (opts, _) = OptionsParser.ParseFrom(new LbOpts(), args);
var cleanRichest = new List<DiscordUser>(); List<DiscordUser> cleanRichest;
// it's pointless to have clean on dm context // it's pointless to have clean on dm context
if (ctx.Guild is null) opts.Clean = false; if (ctx.Guild is null)
opts.Clean = false;
if (opts.Clean) if (opts.Clean)
{ {
var now = DateTime.UtcNow;
await using (var uow = _db.GetDbContext()) await using (var uow = _db.GetDbContext())
{ {
cleanRichest = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 10_000); cleanRichest = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 10_000);
@@ -585,7 +582,7 @@ public partial class Gambling : GamblingModule<GamblingService>
if (!await CheckBetOptional(amount) || amount == 1) if (!await CheckBetOptional(amount) || amount == 1)
return; return;
string getRpsPick(RpsPick p) string GetRpsPick(RpsPick p)
{ {
switch (p) switch (p)
{ {
@@ -614,7 +611,7 @@ public partial class Gambling : GamblingModule<GamblingService>
{ {
await _cs.AddAsync(ctx.User.Id, "Rps-draw", amount, true); await _cs.AddAsync(ctx.User.Id, "Rps-draw", amount, true);
embed.WithOkColor(); embed.WithOkColor();
msg = GetText(strs.rps_draw(getRpsPick(pick))); msg = GetText(strs.rps_draw(GetRpsPick(pick)));
} }
else if ((pick == RpsPick.Paper && nadekoPick == RpsPick.Rock) else if ((pick == RpsPick.Paper && nadekoPick == RpsPick.Rock)
|| (pick == RpsPick.Rock && nadekoPick == RpsPick.Scissors) || (pick == RpsPick.Rock && nadekoPick == RpsPick.Scissors)
@@ -624,13 +621,13 @@ public partial class Gambling : GamblingModule<GamblingService>
await _cs.AddAsync(ctx.User.Id, "Rps-win", amount, true); await _cs.AddAsync(ctx.User.Id, "Rps-win", amount, true);
embed.WithOkColor(); embed.WithOkColor();
embed.AddField(GetText(strs.won), n(amount)); embed.AddField(GetText(strs.won), n(amount));
msg = GetText(strs.rps_win(ctx.User.Mention, getRpsPick(pick), getRpsPick(nadekoPick))); msg = GetText(strs.rps_win(ctx.User.Mention, GetRpsPick(pick), GetRpsPick(nadekoPick)));
} }
else else
{ {
embed.WithErrorColor(); embed.WithErrorColor();
amount = 0; amount = 0;
msg = GetText(strs.rps_win(ctx.Client.CurrentUser.Mention, getRpsPick(nadekoPick), getRpsPick(pick))); msg = GetText(strs.rps_win(ctx.Client.CurrentUser.Mention, GetRpsPick(nadekoPick), GetRpsPick(pick)));
} }
embed.WithDescription(msg); embed.WithDescription(msg);

View File

@@ -1,5 +1,6 @@
#nullable disable #nullable disable
using Microsoft.EntityFrameworkCore; using LinqToDB;
using LinqToDB.EntityFrameworkCore;
using NadekoBot.Services.Database.Models; using NadekoBot.Services.Database.Models;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@@ -42,29 +43,30 @@ public class RemindService : INService
if (reminders.Count == 0) if (reminders.Count == 0)
continue; continue;
Log.Information($"Executing {reminders.Count} reminders."); Log.Information("Executing {ReminderCount} reminders", reminders.Count);
// make groups of 5, with 1.5 second inbetween each one to ensure against ratelimits // make groups of 5, with 1.5 second inbetween each one to ensure against ratelimits
foreach (var group in reminders.Chunk(5)) foreach (var group in reminders.Chunk(5))
{ {
var executedReminders = group.ToList(); var executedReminders = group.ToList();
await executedReminders.Select(ReminderTimerAction).WhenAll(); await executedReminders.Select(ReminderTimerAction).WhenAll();
await RemoveReminders(executedReminders); await RemoveReminders(executedReminders.Select(x => x.Id));
await Task.Delay(1500); await Task.Delay(1500);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Warning($"Error in reminder loop: {ex.Message}"); Log.Warning(ex, "Error in reminder loop: {ErrorMessage}", ex.Message);
Log.Warning(ex.ToString());
} }
} }
} }
private async Task RemoveReminders(List<Reminder> reminders) private async Task RemoveReminders(IEnumerable<int> reminders)
{ {
await using var uow = _db.GetDbContext(); await using var uow = _db.GetDbContext();
uow.Set<Reminder>().RemoveRange(reminders); await uow.Reminders
.ToLinqToDBTable()
.DeleteAsync(x => reminders.Contains(x.Id));
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
@@ -73,9 +75,12 @@ public class RemindService : INService
{ {
using var uow = _db.GetDbContext(); using var uow = _db.GetDbContext();
return uow.Reminders return uow.Reminders
.FromSqlInterpolated( .ToLinqToDBTable()
$"select * from reminders where ((serverid >> 22) % {_creds.TotalShards}) == {_client.ShardId} and \"when\" < {now};") .Where(x => (x.ServerId / 4194304 % (ulong)_creds.TotalShards == (ulong)_client.ShardId)
.ToListAsync(); && x.When < now)
// .FromSqlInterpolated(
// $"select * from reminders where ((serverid >> 22) % {_creds.TotalShards}) == {_client.ShardId} and \"when\" < {now};")
.ToListAsyncLinqToDB();
} }
public bool TryParseRemindMessage(string input, out RemindObject obj) public bool TryParseRemindMessage(string input, out RemindObject obj)
@@ -91,7 +96,7 @@ public class RemindService : INService
if (string.IsNullOrWhiteSpace(what)) if (string.IsNullOrWhiteSpace(what))
{ {
Log.Warning("No message provided for the reminder."); Log.Warning("No message provided for the reminder");
return false; return false;
} }
@@ -106,13 +111,13 @@ public class RemindService : INService
if (!int.TryParse(m.Groups[groupName].Value, out var value)) if (!int.TryParse(m.Groups[groupName].Value, out var value))
{ {
Log.Warning($"Reminder regex group {groupName} has invalid value."); Log.Warning("Reminder regex group {GroupName} has invalid value", groupName);
return false; return false;
} }
if (value < 1) if (value < 1)
{ {
Log.Warning("Reminder time value has to be an integer greater than 0."); Log.Warning("Reminder time value has to be an integer greater than 0");
return false; return false;
} }
@@ -155,7 +160,10 @@ public class RemindService : INService
(await ch.GetUserAsync(r.UserId))?.ToString() ?? r.UserId.ToString()), (await ch.GetUserAsync(r.UserId))?.ToString() ?? r.UserId.ToString()),
r.Message); r.Message);
} }
catch (Exception ex) { Log.Information(ex.Message + $"({r.Id})"); } catch (Exception ex)
{
Log.Warning(ex, "Error executing reminder {ReminderId}: {ErrorMessage}", r.Id, ex.Message);
}
} }
public struct RemindObject public struct RemindObject

View File

@@ -50,6 +50,7 @@
<PackageReference Include="Scrutor" Version="3.3.0" /> <PackageReference Include="Scrutor" Version="3.3.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" /> <PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
<PackageReference Include="Serilog.Sinks.Seq" Version="5.1.0" /> <PackageReference Include="Serilog.Sinks.Seq" Version="5.1.0" />
<PackageReference Include="SerilogAnalyzer" Version="0.15.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.4" /> <PackageReference Include="SixLabors.ImageSharp" Version="1.0.4" />
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta0010" /> <PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta0010" />
<PackageReference Include="StackExchange.Redis" Version="2.2.88" /> <PackageReference Include="StackExchange.Redis" Version="2.2.88" />