Use LogSource Enum for logger and improve logging messages

This commit is contained in:
runebaas 2018-05-06 01:47:13 +02:00
parent 0fe273151c
commit 2b85caeb29
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
16 changed files with 122 additions and 95 deletions

View file

@ -46,7 +46,7 @@ namespace Geekbot.net.Commands.Admin
{ {
_redis.StringSet("Game", key); _redis.StringSet("Game", key);
await _client.SetGameAsync(key); await _client.SetGameAsync(key);
_logger.Information("Geekbot", $"Changed game to {key}"); _logger.Information(LogSource.Geekbot, $"Changed game to {key}");
await ReplyAsync($"Now Playing {key}"); await ReplyAsync($"Now Playing {key}");
} }
@ -59,11 +59,11 @@ namespace Geekbot.net.Commands.Admin
var failed = 0; var failed = 0;
try try
{ {
_logger.Warning("UserRepository", "Populating User Repositry"); _logger.Warning(LogSource.UserRepository, "Populating User Repositry");
await ReplyAsync("Starting Population of User Repository"); await ReplyAsync("Starting Population of User Repository");
foreach (var guild in _client.Guilds) foreach (var guild in _client.Guilds)
{ {
_logger.Information("UserRepository", $"Populating users from {guild.Name}"); _logger.Information(LogSource.UserRepository, $"Populating users from {guild.Name}");
foreach (var user in guild.Users) foreach (var user in guild.Users)
{ {
var succeded = await _userRepository.Update(user); var succeded = await _userRepository.Update(user);
@ -71,7 +71,7 @@ namespace Geekbot.net.Commands.Admin
} }
} }
_logger.Warning("UserRepository", "Finished Updating User Repositry"); _logger.Warning(LogSource.UserRepository, "Finished Updating User Repositry");
await ReplyAsync( await ReplyAsync(
$"Successfully Populated User Repository with {success} Users in {_client.Guilds.Count} Guilds (Failed: {failed})"); $"Successfully Populated User Repository with {success} Users in {_client.Guilds.Count} Guilds (Failed: {failed})");
} }

View file

@ -102,7 +102,7 @@ namespace Geekbot.net.Commands.User.Ranking
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Warning("Geekbot", $"Could not retrieve user {user.Name}", e); _logger.Warning(LogSource.Geekbot, $"Could not retrieve user {user.Name}", e);
} }
} }

View file

@ -62,14 +62,14 @@ namespace Geekbot.net
message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return Task.CompletedTask; message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return Task.CompletedTask;
var context = new CommandContext(_client, message); var context = new CommandContext(_client, message);
var commandExec = _commands.ExecuteAsync(context, argPos, _servicesProvider); var commandExec = _commands.ExecuteAsync(context, argPos, _servicesProvider);
_logger.Information("Command", _logger.Information(LogSource.Command,
context.Message.Content.Split(" ")[0].Replace("!", ""), context.Message.Content.Split(" ")[0].Replace("!", ""),
SimpleConextConverter.ConvertContext(context)); SimpleConextConverter.ConvertContext(context));
return Task.CompletedTask; return Task.CompletedTask;
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error("Geekbot", "Failed to run commands", e); _logger.Error(LogSource.Geekbot, "Failed to Process Message", e);
return Task.CompletedTask; return Task.CompletedTask;
} }
} }
@ -81,7 +81,7 @@ namespace Geekbot.net
if (message == null) return Task.CompletedTask; if (message == null) return Task.CompletedTask;
if (message.Channel.Name.StartsWith('@')) if (message.Channel.Name.StartsWith('@'))
{ {
_logger.Information("Message", "DM-Channel - {message.Channel.Name} - {message.Content}"); _logger.Information(LogSource.Message, $"[DM-Channel] {message.Content}", SimpleConextConverter.ConvertSocketMessage(message));
return Task.CompletedTask; return Task.CompletedTask;
} }
var channel = (SocketGuildChannel) message.Channel; var channel = (SocketGuildChannel) message.Channel;
@ -90,11 +90,11 @@ namespace Geekbot.net
_redis.HashIncrementAsync($"{channel.Guild.Id}:Messages", 0.ToString()); _redis.HashIncrementAsync($"{channel.Guild.Id}:Messages", 0.ToString());
if (message.Author.IsBot) return Task.CompletedTask; if (message.Author.IsBot) return Task.CompletedTask;
_logger.Information("Message", message.Content, SimpleConextConverter.ConvertSocketMessage(message)); _logger.Information(LogSource.Message, message.Content, SimpleConextConverter.ConvertSocketMessage(message));
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error("Message", "Could not process message stats", e); _logger.Error(LogSource.Message, "Could not process message stats", e);
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -117,11 +117,11 @@ namespace Geekbot.net
} }
} }
_userRepository.Update(user); _userRepository.Update(user);
_logger.Information("Geekbot", $"{user.Username} ({user.Id}) joined {user.Guild.Name} ({user.Guild.Id})"); _logger.Information(LogSource.Geekbot, $"{user.Username} ({user.Id}) joined {user.Guild.Name} ({user.Guild.Id})");
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error("Geekbot", "Failed to send welcome message", e); _logger.Error(LogSource.Geekbot, "Failed to send welcome message", e);
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -149,9 +149,9 @@ namespace Geekbot.net
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error("Geekbot", "Failed to send leave message", e); _logger.Error(LogSource.Geekbot, "Failed to send leave message", e);
} }
_logger.Information("Geekbot", $"{user.Username} ({user.Id}) joined {user.Guild.Name} ({user.Guild.Id})"); _logger.Information(LogSource.Geekbot, $"{user.Username} ({user.Id}) joined {user.Guild.Name} ({user.Guild.Id})");
} }
// //
@ -187,7 +187,7 @@ namespace Geekbot.net
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error("Geekbot", "Failed to send delete message...", e); _logger.Error(LogSource.Geekbot, "Failed to send delete message...", e);
} }
} }

View file

@ -42,10 +42,10 @@ namespace Geekbot.net.Lib.Clients
} }
_animeSearch = new AnimeSearchMethodsAsync(_credentials); _animeSearch = new AnimeSearchMethodsAsync(_credentials);
_mangaSearch = new MangaSearchMethodsAsync(_credentials); _mangaSearch = new MangaSearchMethodsAsync(_credentials);
_logger.Debug("Geekbot", "Logged in to MAL"); _logger.Debug(LogSource.Geekbot, "Logged in to MAL");
return true; return true;
} }
_logger.Debug("Geekbot", "No MAL Credentials Set!"); _logger.Debug(LogSource.Geekbot, "No MAL Credentials Set!");
return false; return false;
} }

View file

@ -26,7 +26,7 @@ namespace Geekbot.net.Lib.ErrorHandling
if (!string.IsNullOrEmpty(sentryDsn)) if (!string.IsNullOrEmpty(sentryDsn))
{ {
_raven = new RavenClient(sentryDsn); _raven = new RavenClient(sentryDsn);
_logger.Information("Geekbot", $"Command Errors will be logged to Sentry: {sentryDsn}"); _logger.Information(LogSource.Geekbot, $"Command Errors will be logged to Sentry: {sentryDsn}");
} }
else else
{ {
@ -42,14 +42,21 @@ namespace Geekbot.net.Lib.ErrorHandling
var errorObj = SimpleConextConverter.ConvertContext(context); var errorObj = SimpleConextConverter.ConvertContext(context);
if (e.Message.Contains("50007")) return; if (e.Message.Contains("50007")) return;
if (e.Message.Contains("50013")) return; if (e.Message.Contains("50013")) return;
_logger.Error("Geekbot", "An error ocured", e, errorObj); _logger.Error(LogSource.Geekbot, "An error ocured", e, errorObj);
if (!string.IsNullOrEmpty(errorMessage)) if (!string.IsNullOrEmpty(errorMessage))
{ {
if (_errorsInChat) if (_errorsInChat)
{ {
var resStackTrace = string.IsNullOrEmpty(e.InnerException?.ToString()) ? e.StackTrace : e.InnerException.ToString(); var resStackTrace = string.IsNullOrEmpty(e.InnerException?.ToString()) ? e.StackTrace : e.InnerException?.ToString();
var maxLen = Math.Min(resStackTrace.Length, 1850); if (!string.IsNullOrEmpty(resStackTrace))
context.Channel.SendMessageAsync($"{e.Message}\r\n```\r\n{resStackTrace.Substring(0, maxLen)}\r\n```"); {
var maxLen = Math.Min(resStackTrace.Length, 1850);
context.Channel.SendMessageAsync($"{e.Message}\r\n```\r\n{resStackTrace.Substring(0, maxLen)}\r\n```");
}
else
{
context.Channel.SendMessageAsync(e.Message);
}
} }
else else
{ {
@ -75,7 +82,7 @@ namespace Geekbot.net.Lib.ErrorHandling
catch (Exception ex) catch (Exception ex)
{ {
context.Channel.SendMessageAsync("Something went really really wrong here"); context.Channel.SendMessageAsync("Something went really really wrong here");
_logger.Error("Geekbot", "Errorception", ex); _logger.Error(LogSource.Geekbot, "Errorception", ex);
} }
} }

View file

@ -22,7 +22,7 @@ namespace Geekbot.net.Lib.Localization
{ {
_logger = logger; _logger = logger;
_redis = redis; _redis = redis;
_logger.Information("Geekbot", "Loading Translations"); _logger.Information(LogSource.Geekbot, "Loading Translations");
LoadTranslations(); LoadTranslations();
LoadServerLanguages(clientGuilds); LoadServerLanguages(clientGuilds);
} }
@ -71,7 +71,7 @@ namespace Geekbot.net.Lib.Localization
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error("Geekbot", "Failed to load Translations", e); _logger.Error(LogSource.Geekbot, "Failed to load Translations", e);
Environment.Exit(110); Environment.Exit(110);
} }
} }
@ -100,7 +100,7 @@ namespace Geekbot.net.Lib.Localization
translation = _translations[command][stringName]["EN"]; translation = _translations[command][stringName]["EN"];
if (string.IsNullOrWhiteSpace(translation)) if (string.IsNullOrWhiteSpace(translation))
{ {
_logger.Warning("Geekbot", $"No translation found for {command} - {stringName}"); _logger.Warning(LogSource.Geekbot, $"No translation found for {command} - {stringName}");
} }
return translation; return translation;
} }
@ -114,7 +114,7 @@ namespace Geekbot.net.Lib.Localization
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error("Geekbot", "lol nope", e); _logger.Error(LogSource.Geekbot, "lol nope", e);
return new Dictionary<string, string>(); return new Dictionary<string, string>();
} }
} }
@ -127,7 +127,7 @@ namespace Geekbot.net.Lib.Localization
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error("Geekbot", "lol nope", e); _logger.Error(LogSource.Geekbot, "lol nope", e);
return new Dictionary<string, string>(); return new Dictionary<string, string>();
} }
} }
@ -143,7 +143,7 @@ namespace Geekbot.net.Lib.Localization
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error("Geekbot", "Error while changing language", e); _logger.Error(LogSource.Geekbot, "Error while changing language", e);
return false; return false;
} }
} }

View file

@ -1,5 +1,7 @@
using System.Threading.Tasks; using System;
using System.Threading.Tasks;
using Discord; using Discord;
using Geekbot.net.Commands.Randomness.Cat;
namespace Geekbot.net.Lib.Logger namespace Geekbot.net.Lib.Logger
{ {
@ -14,26 +16,37 @@ namespace Geekbot.net.Lib.Logger
public Task Log(LogMessage message) public Task Log(LogMessage message)
{ {
LogSource source;
try
{
source = Enum.Parse<LogSource>(message.Source);
}
catch
{
source = LogSource.Discord;
_logger.Warning(LogSource.Geekbot, $"Could not parse {message.Source} to a LogSource Enum");
}
var logMessage = $"[{message.Source}] {message.Message}"; var logMessage = $"[{message.Source}] {message.Message}";
switch (message.Severity) switch (message.Severity)
{ {
case LogSeverity.Verbose: case LogSeverity.Verbose:
_logger.Trace(message.Source, message.Message); _logger.Trace(source, message.Message);
break; break;
case LogSeverity.Debug: case LogSeverity.Debug:
_logger.Debug(message.Source, message.Message); _logger.Debug(source, message.Message);
break; break;
case LogSeverity.Info: case LogSeverity.Info:
_logger.Information(message.Source, message.Message); _logger.Information(source, message.Message);
break; break;
case LogSeverity.Critical: case LogSeverity.Critical:
case LogSeverity.Error: case LogSeverity.Error:
case LogSeverity.Warning: case LogSeverity.Warning:
if (logMessage.Contains("VOICE_STATE_UPDATE")) break; if (logMessage.Contains("VOICE_STATE_UPDATE")) break;
_logger.Error(message.Source, message.Message, message.Exception); _logger.Error(source, message.Message, message.Exception);
break; break;
default: default:
_logger.Information(message.Source, $"{logMessage} --- {message.Severity}"); _logger.Information(source, $"{logMessage} --- {message.Severity}");
break; break;
} }
return Task.CompletedTask; return Task.CompletedTask;

View file

@ -18,35 +18,36 @@ namespace Geekbot.net.Lib.Logger
ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
NullValueHandling = NullValueHandling.Include NullValueHandling = NullValueHandling.Include
}; };
Information("Geekbot", "Using GeekbotLogger"); Information(LogSource.Geekbot, "Using GeekbotLogger");
} }
public void Trace(string source, string message, object extra = null) public void Trace(LogSource source, string message, object extra = null)
{ {
_logger.Trace(CreateLogString("Trace", source, message, null, extra)); _logger.Trace(CreateLogString("Trace", source, message, null, extra));
} }
public void Debug(string source, string message, object extra = null) public void Debug(LogSource source, string message, object extra = null)
{ {
_logger.Debug(CreateLogString("Debug", source, message, null, extra)); _logger.Debug(CreateLogString("Debug", source, message, null, extra));
} }
public void Information(string source, string message, object extra = null) public void Information(LogSource source, string message, object extra = null)
{ {
_logger.Info(CreateLogString("Information", source, message, null, extra)); _logger.Info(CreateLogString("Information", source, message, null, extra));
} }
public void Warning(string source, string message, Exception stackTrace = null, object extra = null) public void Warning(LogSource source, string message, Exception stackTrace = null, object extra = null)
{ {
_logger.Warn(CreateLogString("Warning", source, message, stackTrace, extra)); _logger.Warn(CreateLogString("Warning", source, message, stackTrace, extra));
} }
public void Error(string source, string message, Exception stackTrace, object extra = null) public void Error(LogSource source, string message, Exception stackTrace, object extra = null)
{ {
_logger.Error(CreateLogString("Error", source, message, stackTrace, extra)); if (_logAsJson) _logger.Error(CreateLogString("Error", source, message, stackTrace, extra));
else _logger.Error(stackTrace, CreateLogString("Error", source, message, stackTrace, extra));
} }
private string CreateLogString(string type, string source, string message, Exception stackTrace = null, object extra = null) private string CreateLogString(string type, LogSource source, string message, Exception stackTrace = null, object extra = null)
{ {
if (_logAsJson) if (_logAsJson)
{ {
@ -62,7 +63,7 @@ namespace Geekbot.net.Lib.Logger
return JsonConvert.SerializeObject(logObject, Formatting.None, _serializerSettings); return JsonConvert.SerializeObject(logObject, Formatting.None, _serializerSettings);
} }
if (source != "Message") return $"[{source}] - {message}"; if (source != LogSource.Message) return $"[{source}] - {message}";
var m = (MessageDto) extra; var m = (MessageDto) extra;
return $"[{source}] - [{m?.Guild.Name} - {m?.Channel.Name}] {m?.User.Name}: {m?.Message.Content}"; return $"[{source}] - [{m?.Guild.Name} - {m?.Channel.Name}] {m?.User.Name}: {m?.Message.Content}";

View file

@ -4,10 +4,10 @@ namespace Geekbot.net.Lib.Logger
{ {
public interface IGeekbotLogger public interface IGeekbotLogger
{ {
void Trace(string source, string message, object extra = null); void Trace(LogSource source, string message, object extra = null);
void Debug(string source, string message, object extra = null); void Debug(LogSource source, string message, object extra = null);
void Information(string source, string message, object extra = null); void Information(LogSource source, string message, object extra = null);
void Warning(string source, string message, Exception stackTrace = null, object extra = null); void Warning(LogSource source, string message, Exception stackTrace = null, object extra = null);
void Error(string source, string message, Exception stackTrace, object extra = null); void Error(LogSource source, string message, Exception stackTrace, object extra = null);
} }
} }

View file

@ -6,7 +6,7 @@ namespace Geekbot.net.Lib.Logger
{ {
public DateTime Timestamp { get; set; } public DateTime Timestamp { get; set; }
public string Type { get; set; } public string Type { get; set; }
public string Source { get; set; } public LogSource Source { get; set; }
public string Message { get; set; } public string Message { get; set; }
public Exception StackTrace { get; set; } public Exception StackTrace { get; set; }
public object Extra { get; set; } public object Extra { get; set; }

View file

@ -0,0 +1,16 @@
namespace Geekbot.net.Lib.Logger
{
public enum LogSource
{
Geekbot,
Rest,
Gateway,
Discord,
Redis,
Message,
UserRepository,
Command,
Api,
Other
}
}

View file

@ -56,13 +56,13 @@ namespace Geekbot.net.Lib.Logger
}, },
Guild = new MessageDto.IdAndName Guild = new MessageDto.IdAndName
{ {
Id = channel.Guild.Id.ToString(), Id = channel?.Guild?.Id.ToString(),
Name = channel.Guild.Name Name = channel?.Guild?.Name
}, },
Channel = new MessageDto.IdAndName Channel = new MessageDto.IdAndName
{ {
Id = channel.Id.ToString(), Id = channel?.Id.ToString(),
Name = channel.Name Name = channel?.Name
} }
}; };
} }

View file

@ -17,11 +17,11 @@ namespace Geekbot.net.Lib.Media
var rawFortunes = File.ReadAllText(path); var rawFortunes = File.ReadAllText(path);
_fortuneArray = rawFortunes.Split("%"); _fortuneArray = rawFortunes.Split("%");
_totalFortunes = _fortuneArray.Length; _totalFortunes = _fortuneArray.Length;
logger.Trace("Geekbot", $"Loaded {_totalFortunes} Fortunes"); logger.Trace(LogSource.Geekbot, $"Loaded {_totalFortunes} Fortunes");
} }
else else
{ {
logger.Information("Geekbot", $"Fortunes File not found at {path}"); logger.Information(LogSource.Geekbot, $"Fortunes File not found at {path}");
} }
} }

View file

@ -22,7 +22,7 @@ namespace Geekbot.net.Lib.Media
_random = new Random(); _random = new Random();
_logger = logger; _logger = logger;
logger.Information("Geekbot", "Loading Media Files"); logger.Information(LogSource.Geekbot, "Loading Media Files");
LoadCheckem(); LoadCheckem();
LoadPandas(); LoadPandas();
@ -38,56 +38,56 @@ namespace Geekbot.net.Lib.Media
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/checkEmPics")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/checkEmPics"));
_checkemImages = rawLinks.Split("\n"); _checkemImages = rawLinks.Split("\n");
_logger.Trace("Geekbot", $"Loaded {_checkemImages.Length} CheckEm Images"); _logger.Trace(LogSource.Geekbot, $"Loaded {_checkemImages.Length} CheckEm Images");
} }
private void LoadPandas() private void LoadPandas()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pandas")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pandas"));
_pandaImages = rawLinks.Split("\n"); _pandaImages = rawLinks.Split("\n");
_logger.Trace("Geekbot", $"Loaded {_pandaImages.Length} Panda Images"); _logger.Trace(LogSource.Geekbot, $"Loaded {_pandaImages.Length} Panda Images");
} }
private void BakeCroissants() private void BakeCroissants()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/croissant")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/croissant"));
_croissantImages = rawLinks.Split("\n"); _croissantImages = rawLinks.Split("\n");
_logger.Trace("Geekbot", $"Loaded {_croissantImages.Length} Croissant Images"); _logger.Trace(LogSource.Geekbot, $"Loaded {_croissantImages.Length} Croissant Images");
} }
private void LoadSquirrels() private void LoadSquirrels()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/squirrel")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/squirrel"));
_squirrelImages = rawLinks.Split("\n"); _squirrelImages = rawLinks.Split("\n");
_logger.Trace("Geekbot", $"Loaded {_squirrelImages.Length} Squirrel Images"); _logger.Trace(LogSource.Geekbot, $"Loaded {_squirrelImages.Length} Squirrel Images");
} }
private void LoadPumpkins() private void LoadPumpkins()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pumpkin")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pumpkin"));
_pumpkinImages = rawLinks.Split("\n"); _pumpkinImages = rawLinks.Split("\n");
_logger.Trace("Geekbot", $"Loaded {_pumpkinImages.Length} Pumpkin Images"); _logger.Trace(LogSource.Geekbot, $"Loaded {_pumpkinImages.Length} Pumpkin Images");
} }
private void LoadTurtles() private void LoadTurtles()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/turtles")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/turtles"));
_turtlesImages = rawLinks.Split("\n"); _turtlesImages = rawLinks.Split("\n");
_logger.Trace("Geekbot", $"Loaded {_turtlesImages.Length} Turtle Images"); _logger.Trace(LogSource.Geekbot, $"Loaded {_turtlesImages.Length} Turtle Images");
} }
private void LoadPinguins() private void LoadPinguins()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pinguins")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/pinguins"));
_pinguinImages = rawLinks.Split("\n"); _pinguinImages = rawLinks.Split("\n");
_logger.Trace("Geekbot", $"Loaded {_pinguinImages.Length} Pinguin Images"); _logger.Trace(LogSource.Geekbot, $"Loaded {_pinguinImages.Length} Pinguin Images");
} }
private void LoadFoxes() private void LoadFoxes()
{ {
var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/foxes")); var rawLinks = File.ReadAllText(Path.GetFullPath("./Storage/foxes"));
_foxImages = rawLinks.Split("\n"); _foxImages = rawLinks.Split("\n");
_logger.Trace("Geekbot", $"Loaded {_foxImages.Length} Foxes Images"); _logger.Trace(LogSource.Geekbot, $"Loaded {_foxImages.Length} Foxes Images");
} }
public string GetCheckem() public string GetCheckem()

View file

@ -36,12 +36,12 @@ namespace Geekbot.net.Lib.UserRepository
} }
Store(savedUser); Store(savedUser);
_logger.Information("UserRepository", "Updated User", savedUser); _logger.Information(LogSource.UserRepository, "Updated User", savedUser);
return Task.FromResult(true); return Task.FromResult(true);
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Warning("UserRepository", $"Failed to update user: {user.Username}#{user.Discriminator} ({user.Id})", e); _logger.Warning(LogSource.UserRepository, $"Failed to update user: {user.Username}#{user.Discriminator} ({user.Id})", e);
return Task.FromResult(false); return Task.FromResult(false);
} }
} }
@ -103,7 +103,7 @@ namespace Geekbot.net.Lib.UserRepository
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Warning("UserRepository", "Failed to get {userId} from repository", e); _logger.Warning(LogSource.UserRepository, $"Failed to get {userId} from repository", e);
return new UserRepositoryUser(); return new UserRepositoryUser();
} }
} }

View file

@ -55,14 +55,14 @@ namespace Geekbot.net
Console.WriteLine(logo.ToString()); Console.WriteLine(logo.ToString());
var sumologicActive = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GEEKBOT_SUMO")); var sumologicActive = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GEEKBOT_SUMO"));
var logger = new GeekbotLogger(runParameters, sumologicActive); var logger = new GeekbotLogger(runParameters, sumologicActive);
logger.Information("Geekbot", "Starting..."); logger.Information(LogSource.Geekbot, "Starting...");
try try
{ {
new Program().MainAsync(runParameters, logger).GetAwaiter().GetResult(); new Program().MainAsync(runParameters, logger).GetAwaiter().GetResult();
} }
catch (Exception e) catch (Exception e)
{ {
logger.Error("Geekbot", "RIP", e); logger.Error(LogSource.Geekbot, "RIP", e);
} }
} }
@ -70,7 +70,7 @@ namespace Geekbot.net
{ {
_logger = logger; _logger = logger;
_runParameters = runParameters; _runParameters = runParameters;
logger.Information("Geekbot", "Initing Stuff"); logger.Information(LogSource.Geekbot, "Initing Stuff");
var discordLogger = new DiscordLogger(logger); var discordLogger = new DiscordLogger(logger);
_client = new DiscordSocketClient(new DiscordSocketConfig _client = new DiscordSocketClient(new DiscordSocketConfig
@ -85,11 +85,11 @@ namespace Geekbot.net
{ {
var redisMultiplexer = ConnectionMultiplexer.Connect("127.0.0.1:6379"); var redisMultiplexer = ConnectionMultiplexer.Connect("127.0.0.1:6379");
_redis = redisMultiplexer.GetDatabase(6); _redis = redisMultiplexer.GetDatabase(6);
logger.Information("Redis", $"Connected to db {_redis.Database}"); logger.Information(LogSource.Redis, $"Connected to db {_redis.Database}");
} }
catch (Exception e) catch (Exception e)
{ {
logger.Error("Redis", "Redis Connection Failed", e); logger.Error(LogSource.Redis, "Redis Connection Failed", e);
Environment.Exit(102); Environment.Exit(102);
} }
@ -128,7 +128,7 @@ namespace Geekbot.net
_services.AddSingleton<IWikipediaClient>(wikipediaClient); _services.AddSingleton<IWikipediaClient>(wikipediaClient);
_services.AddSingleton<IAudioUtils>(audioUtils); _services.AddSingleton<IAudioUtils>(audioUtils);
logger.Information("Geekbot", "Connecting to Discord"); logger.Information(LogSource.Geekbot, "Connecting to Discord");
await Login(); await Login();
@ -145,9 +145,9 @@ namespace Geekbot.net
if (isConneted) if (isConneted)
{ {
await _client.SetGameAsync(_redis.StringGet("Game")); await _client.SetGameAsync(_redis.StringGet("Game"));
_logger.Information("Geekbot", $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers");
_logger.Information("Geekbot", "Registering Stuff"); _logger.Information(LogSource.Geekbot, "Registering Stuff");
var translationHandler = new TranslationHandler(_client.Guilds, _redis, _logger); var translationHandler = new TranslationHandler(_client.Guilds, _redis, _logger);
var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors); var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors);
var reactionListener = new ReactionListener(_redis); var reactionListener = new ReactionListener(_redis);
@ -172,21 +172,21 @@ namespace Geekbot.net
if (_firstStart || _runParameters.Reset) if (_firstStart || _runParameters.Reset)
{ {
_logger.Information("Geekbot", "Finishing setup"); _logger.Information(LogSource.Geekbot, "Finishing setup");
await FinishSetup(); await FinishSetup();
_logger.Information("Geekbot", "Setup finished"); _logger.Information(LogSource.Geekbot, "Setup finished");
} }
if (!_runParameters.DisableApi) if (!_runParameters.DisableApi)
{ {
StartWebApi(); StartWebApi();
} }
_logger.Information("Geekbot", "Done and ready for use"); _logger.Information(LogSource.Geekbot, "Done and ready for use");
} }
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error("Discord", "Could not connect...", e); _logger.Error(LogSource.Geekbot, "Could not connect...", e);
Environment.Exit(103); Environment.Exit(103);
} }
} }
@ -200,33 +200,23 @@ namespace Geekbot.net
private void StartWebApi() private void StartWebApi()
{ {
_logger.Information("API", "Starting Webserver"); _logger.Information(LogSource.Api, "Starting Webserver");
var webApiUrl = new Uri("http://localhost:12995"); var webApiUrl = new Uri("http://localhost:12995");
new NancyHost(webApiUrl).Start(); new NancyHost(webApiUrl).Start();
_logger.Information("API", $"Webserver now running on {webApiUrl}"); _logger.Information(LogSource.Api, $"Webserver now running on {webApiUrl}");
} }
private async Task<Task> FinishSetup() private async Task<Task> FinishSetup()
{ {
var appInfo = await _client.GetApplicationInfoAsync();
_logger.Information("Setup", $"Just a moment while i setup everything {appInfo.Owner.Username}");
try try
{ {
// ToDo: Set bot avatar
var appInfo = await _client.GetApplicationInfoAsync();
_redis.StringSet("botOwner", appInfo.Owner.Id); _redis.StringSet("botOwner", appInfo.Owner.Id);
var req = WebRequest.Create(appInfo.IconUrl);
using (var stream = req.GetResponse().GetResponseStream())
{
await _client.CurrentUser.ModifyAsync(user =>
{
user.Avatar = new Image(stream);
user.Username = appInfo.Name.ToString();
});
}
_logger.Information("Setup", "Everything done, enjoy!");
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Warning("Setup", "Oha, it seems like something went wrong while running the setup, geekbot will work never the less though", e); _logger.Warning(LogSource.Geekbot, "Setup Failed, couldn't retrieve discord application data", e);
} }
return Task.CompletedTask; return Task.CompletedTask;
} }