Better logging

This commit is contained in:
benbierens 2023-12-18 11:27:28 +01:00
parent 03283414cb
commit 6298744918
No known key found for this signature in database
GPG Key ID: FE44815D96D0A1AA
9 changed files with 74 additions and 24 deletions

View File

@ -0,0 +1,17 @@
namespace Logging
{
public class FileLog : BaseLog
{
public FileLog(string fullFilename)
{
FullFilename = fullFilename;
}
public string FullFilename { get; }
protected override string GetFullName()
{
return FullFilename;
}
}
}

View File

@ -1,4 +1,5 @@
using Discord.WebSocket; using Discord;
using Discord.WebSocket;
namespace BiblioTech namespace BiblioTech
{ {
@ -7,6 +8,7 @@ namespace BiblioTech
private SocketGuild guild = null!; private SocketGuild guild = null!;
private ulong[] adminIds = Array.Empty<ulong>(); private ulong[] adminIds = Array.Empty<ulong>();
private DateTime lastUpdate = DateTime.MinValue; private DateTime lastUpdate = DateTime.MinValue;
private ISocketMessageChannel adminChannel = null!;
public void SetGuild(SocketGuild guild) public void SetGuild(SocketGuild guild)
{ {
@ -20,11 +22,21 @@ namespace BiblioTech
return adminIds.Contains(userId); return adminIds.Contains(userId);
} }
public bool IsAdminChannel(ISocketMessageChannel channel) public bool IsAdminChannel(IChannel channel)
{ {
return channel.Name == Program.Config.AdminChannelName; return channel.Name == Program.Config.AdminChannelName;
} }
public ISocketMessageChannel GetAdminChannel()
{
return adminChannel;
}
public void SetAdminChannel(ISocketMessageChannel adminChannel)
{
this.adminChannel = adminChannel;
}
private bool ShouldUpdate() private bool ShouldUpdate()
{ {
return !adminIds.Any() || (DateTime.UtcNow - lastUpdate) > TimeSpan.FromMinutes(10); return !adminIds.Any() || (DateTime.UtcNow - lastUpdate) > TimeSpan.FromMinutes(10);

View File

@ -17,22 +17,24 @@ namespace BiblioTech
try try
{ {
Program.Log.Log($"Responding to '{Name}'");
var context = new CommandContext(command, command.Data.Options); var context = new CommandContext(command, command.Data.Options);
await command.RespondAsync(StartingMessage, ephemeral: IsEphemeral(context)); await command.RespondAsync(StartingMessage, ephemeral: IsEphemeral(context));
await Invoke(context); await Invoke(context);
} }
catch (Exception ex) catch (Exception ex)
{ {
var msg = "Failed with exception: " + ex;
if (IsInAdminChannel(command)) if (IsInAdminChannel(command))
{ {
var msg = "Failed with exception: " + ex;
await command.FollowupAsync(msg.Substring(0, Math.Min(1900, msg.Length))); await command.FollowupAsync(msg.Substring(0, Math.Min(1900, msg.Length)));
} }
else else
{ {
await command.FollowupAsync("Something failed while trying to do that...", ephemeral: true); await command.FollowupAsync("Something failed while trying to do that...", ephemeral: true);
await Program.AdminChecker.GetAdminChannel().SendMessageAsync(msg);
} }
Console.WriteLine(ex); Program.Log.Error(msg);
} }
} }

View File

@ -23,18 +23,26 @@ namespace BiblioTech
{ {
var guild = client.Guilds.Single(g => g.Name == Program.Config.ServerName); var guild = client.Guilds.Single(g => g.Name == Program.Config.ServerName);
Program.AdminChecker.SetGuild(guild); Program.AdminChecker.SetGuild(guild);
Program.Log.Log($"Initializing for guild: '{guild.Name}'");
var adminChannels = guild.TextChannels.Where(Program.AdminChecker.IsAdminChannel).ToArray();
if (adminChannels == null || !adminChannels.Any()) throw new Exception("No admin message channel");
Program.AdminChecker.SetAdminChannel(adminChannels.First());
var builders = commands.Select(c => var builders = commands.Select(c =>
{ {
var msg = $"Building command '{c.Name}' with options: ";
var builder = new SlashCommandBuilder() var builder = new SlashCommandBuilder()
.WithName(c.Name) .WithName(c.Name)
.WithDescription(c.Description); .WithDescription(c.Description);
foreach (var option in c.Options) foreach (var option in c.Options)
{ {
msg += option.Name + " ";
builder.AddOption(option.Build()); builder.AddOption(option.Build());
} }
Program.Log.Log(msg);
return builder; return builder;
}); });
@ -48,7 +56,7 @@ namespace BiblioTech
catch (HttpException exception) catch (HttpException exception)
{ {
var json = JsonConvert.SerializeObject(exception.Errors, Formatting.Indented); var json = JsonConvert.SerializeObject(exception.Errors, Formatting.Indented);
Console.WriteLine(json); Program.Log.Error(json);
} }
} }

View File

@ -1,7 +1,5 @@
using BiblioTech.Options; using BiblioTech.Options;
using CodexContractsPlugin; using CodexContractsPlugin;
using CodexPlugin;
using Core;
using GethPlugin; using GethPlugin;
namespace BiblioTech.Commands namespace BiblioTech.Commands

View File

@ -48,7 +48,7 @@ namespace BiblioTech.Commands
if (ShouldMintTestTokens(contracts, addr)) if (ShouldMintTestTokens(contracts, addr))
{ {
var transaction = contracts.MintTestTokens(addr, defaultTestTokensToMint); var transaction = contracts.MintTestTokens(addr, defaultTestTokensToMint);
report.Add($"Minted {defaultTestTokensToMint}. ({FormatTransactionLink(transaction)})"); report.Add($"Minted {defaultTestTokensToMint} {FormatTransactionLink(transaction)}");
return new Transaction<TestToken>(defaultTestTokensToMint, transaction); return new Transaction<TestToken>(defaultTestTokensToMint, transaction);
} }
@ -61,7 +61,7 @@ namespace BiblioTech.Commands
if (ShouldSendEth(gethNode, addr)) if (ShouldSendEth(gethNode, addr))
{ {
var transaction = gethNode.SendEth(addr, defaultEthToSend); var transaction = gethNode.SendEth(addr, defaultEthToSend);
report.Add($"Sent {defaultEthToSend}. ({FormatTransactionLink(transaction)})"); report.Add($"Sent {defaultEthToSend} {FormatTransactionLink(transaction)}");
return new Transaction<Ether>(defaultEthToSend, transaction); return new Transaction<Ether>(defaultEthToSend, transaction);
} }
report.Add("Eth balance is over threshold. (No Eth sent.)"); report.Add("Eth balance is over threshold. (No Eth sent.)");
@ -82,7 +82,8 @@ namespace BiblioTech.Commands
private string FormatTransactionLink(string transaction) private string FormatTransactionLink(string transaction)
{ {
return $"https://explorer.testnet.codex.storage/tx/{transaction}"; var url = $"https://explorer.testnet.codex.storage/tx/{transaction}";
return $"- [View on block explorer]({url}){Environment.NewLine}Transaction ID - `{transaction}`";
} }
} }
} }

View File

@ -19,12 +19,6 @@ namespace BiblioTech
[Uniform("admin-channel-name", "ac", "ADMINCHANNELNAME", true, "Name of the Discord server channel where admin commands are allowed.")] [Uniform("admin-channel-name", "ac", "ADMINCHANNELNAME", true, "Name of the Discord server channel where admin commands are allowed.")]
public string AdminChannelName { get; set; } = "admin-channel"; public string AdminChannelName { get; set; } = "admin-channel";
[Uniform("kube-config", "kc", "KUBECONFIG", true, "Path to Kubeconfig file. Use a Kubeconfig with read-only access.")]
public string KubeConfigFile { get; set; } = "null";
[Uniform("kube-namespace", "kn", "KUBENAMESPACE", true, "Kubernetes namespace.")]
public string KubeNamespace { get; set; } = string.Empty;
public string EndpointsPath public string EndpointsPath
{ {
get get
@ -40,5 +34,13 @@ namespace BiblioTech
return Path.Combine(DataPath, "users"); return Path.Combine(DataPath, "users");
} }
} }
public string LogPath
{
get
{
return Path.Combine(DataPath, "logs");
}
}
} }
} }

View File

@ -2,6 +2,7 @@
using BiblioTech.Commands; using BiblioTech.Commands;
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
using Logging;
namespace BiblioTech namespace BiblioTech
{ {
@ -11,13 +12,19 @@ namespace BiblioTech
public static Configuration Config { get; private set; } = null!; public static Configuration Config { get; private set; } = null!;
public static UserRepo UserRepo { get; } = new UserRepo(); public static UserRepo UserRepo { get; } = new UserRepo();
public static AdminChecker AdminChecker { get; } = new AdminChecker(); public static AdminChecker AdminChecker { get; private set; } = null!;
public static ILog Log { get; private set; } = null!;
public static Task Main(string[] args) public static Task Main(string[] args)
{ {
var uniformArgs = new ArgsUniform<Configuration>(PrintHelp, args); var uniformArgs = new ArgsUniform<Configuration>(PrintHelp, args);
Config = uniformArgs.Parse(); Config = uniformArgs.Parse();
Log = new LogSplitter(
new FileLog(Path.Combine(Config.LogPath, "discordbot.log")),
new ConsoleLog()
);
EnsurePath(Config.DataPath); EnsurePath(Config.DataPath);
EnsurePath(Config.UserDataPath); EnsurePath(Config.UserDataPath);
EnsurePath(Config.EndpointsPath); EnsurePath(Config.EndpointsPath);
@ -27,9 +34,9 @@ namespace BiblioTech
public async Task MainAsync() public async Task MainAsync()
{ {
Console.WriteLine("Starting Codex Discord Bot..."); Log.Log("Starting Codex Discord Bot...");
client = new DiscordSocketClient(); client = new DiscordSocketClient();
client.Log += Log; client.Log += ClientLog;
var associateCommand = new UserAssociateCommand(); var associateCommand = new UserAssociateCommand();
var sprCommand = new SprCommand(); var sprCommand = new SprCommand();
@ -43,18 +50,21 @@ namespace BiblioTech
await client.LoginAsync(TokenType.Bot, Config.ApplicationToken); await client.LoginAsync(TokenType.Bot, Config.ApplicationToken);
await client.StartAsync(); await client.StartAsync();
Console.WriteLine("Running...");
AdminChecker = new AdminChecker();
Log.Log("Running...");
await Task.Delay(-1); await Task.Delay(-1);
} }
private static void PrintHelp() private static void PrintHelp()
{ {
Console.WriteLine("BiblioTech - Codex Discord Bot"); Log.Log("BiblioTech - Codex Discord Bot");
} }
private Task Log(LogMessage msg) private Task ClientLog(LogMessage msg)
{ {
Console.WriteLine(msg.ToString()); Log.Log("DiscordClient: " + msg.ToString());
return Task.CompletedTask; return Task.CompletedTask;
} }

View File

@ -19,7 +19,7 @@
public static string Get() public static string Get()
{ {
return messages[random.Next(messages.Length)]; return "Hold on: " + messages[random.Next(messages.Length)];
} }
} }
} }