Replace all ocurences of the Serilog with GeekbotLogger

This commit is contained in:
runebaas 2018-01-20 01:38:49 +01:00
parent 82b2b4c815
commit 07ca1e1548
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
13 changed files with 105 additions and 118 deletions

View file

@ -14,13 +14,11 @@ namespace Geekbot.net.Commands
public class Overwatch : ModuleBase public class Overwatch : ModuleBase
{ {
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly ILogger _logger;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
public Overwatch(IErrorHandler errorHandler, ILogger logger, IDatabase redis, IUserRepository userRepository) public Overwatch(IErrorHandler errorHandler, IDatabase redis, IUserRepository userRepository)
{ {
_errorHandler = errorHandler; _errorHandler = errorHandler;
_logger = logger;
_userRepository = userRepository; _userRepository = userRepository;
} }
@ -117,7 +115,6 @@ namespace Geekbot.net.Commands
{ {
var player = await owClient.GetPlayerAsync(battletag); var player = await owClient.GetPlayerAsync(battletag);
if (player.Username == null) return null; if (player.Username == null) return null;
_logger.Debug($"[OW] Username = {player.Username}");
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder() eb.WithAuthor(new EmbedAuthorBuilder()
.WithIconUrl(player.ProfilePortraitUrl) .WithIconUrl(player.ProfilePortraitUrl)

View file

@ -15,11 +15,11 @@ namespace Geekbot.net.Commands
{ {
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly ILogger _logger; private readonly IGeekbotLogger _logger;
private readonly IDatabase _redis; private readonly IDatabase _redis;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
public Owner(IDatabase redis, DiscordSocketClient client, ILogger logger, IUserRepository userRepositry, public Owner(IDatabase redis, DiscordSocketClient client, IGeekbotLogger logger, IUserRepository userRepositry,
IErrorHandler errorHandler) IErrorHandler errorHandler)
{ {
_redis = redis; _redis = redis;
@ -61,7 +61,7 @@ namespace Geekbot.net.Commands
_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("Geekbot", $"Changed game to {key}");
await ReplyAsync($"Now Playing {key}"); await ReplyAsync($"Now Playing {key}");
} }
@ -91,11 +91,11 @@ namespace Geekbot.net.Commands
var failed = 0; var failed = 0;
try try
{ {
_logger.Warning("[UserRepository] Populating User Repositry"); _logger.Warning("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("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);
@ -103,7 +103,7 @@ namespace Geekbot.net.Commands
} }
} }
_logger.Warning("[UserRepository] Finished Updating User Repositry"); _logger.Warning("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

@ -15,12 +15,12 @@ namespace Geekbot.net.Commands
{ {
private readonly IEmojiConverter _emojiConverter; private readonly IEmojiConverter _emojiConverter;
private readonly IErrorHandler _errorHandler; private readonly IErrorHandler _errorHandler;
private readonly ILogger _logger; private readonly IGeekbotLogger _logger;
private readonly IDatabase _redis; private readonly IDatabase _redis;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
public Rank(IDatabase redis, IErrorHandler errorHandler, ILogger logger, IUserRepository userRepository, public Rank(IDatabase redis, IErrorHandler errorHandler, IGeekbotLogger logger, IUserRepository userRepository,
IEmojiConverter emojiConverter, DiscordSocketClient client) IEmojiConverter emojiConverter, DiscordSocketClient client)
{ {
_redis = redis; _redis = redis;
@ -91,7 +91,7 @@ namespace Geekbot.net.Commands
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Warning(e, $"Could not retrieve user {user.Name}"); _logger.Warning("Geekbot", $"Could not retrieve user {user.Name}", e);
} }
} }

View file

@ -14,18 +14,16 @@ namespace Geekbot.net
public class Handlers public class Handlers
{ {
private readonly IDiscordClient _client; private readonly IDiscordClient _client;
private readonly ILogger _logger; private readonly IGeekbotLogger _logger;
private readonly IGeekbotLogger _gLogger;
private readonly IDatabase _redis; private readonly IDatabase _redis;
private readonly IServiceProvider _servicesProvider; private readonly IServiceProvider _servicesProvider;
private readonly CommandService _commands; private readonly CommandService _commands;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
public Handlers(IDiscordClient client, ILogger logger, IDatabase redis, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, IGeekbotLogger gLogger) public Handlers(IDiscordClient client, IGeekbotLogger logger, IDatabase redis, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository)
{ {
_client = client; _client = client;
_logger = logger; _logger = logger;
_gLogger = gLogger;
_redis = redis; _redis = redis;
_servicesProvider = servicesProvider; _servicesProvider = servicesProvider;
_commands = commands; _commands = commands;
@ -62,7 +60,7 @@ namespace Geekbot.net
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error(e, "[Geekbot] Failed to run commands"); _logger.Error("Geekbot", "Failed to run commands", e);
return Task.CompletedTask; return Task.CompletedTask;
} }
} }
@ -74,8 +72,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( _logger.Information("Message", "DM-Channel - {message.Channel.Name} - {message.Content}");
$"[Message] DM-Channel - {message.Channel.Name} - {message.Content}");
return Task.CompletedTask; return Task.CompletedTask;
} }
var channel = (SocketGuildChannel) message.Channel; var channel = (SocketGuildChannel) message.Channel;
@ -84,12 +81,12 @@ 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;
_gLogger.Info("Message", message.Content, SimpleConextConverter.ConvertSocketMessage(message)); _logger.Information("Message", message.Content, SimpleConextConverter.ConvertSocketMessage(message));
// _logger.Information($"[Message] {channel.Guild.Name} ({channel.Guild.Id}) - {message.Channel} ({message.Channel.Id}) - {message.Author.Username}#{message.Author.Discriminator} ({message.Author.Id}) - {message.Content}"); // _logger.Information($"[Message] {channel.Guild.Name} ({channel.Guild.Id}) - {message.Channel} ({message.Channel.Id}) - {message.Author.Username}#{message.Author.Discriminator} ({message.Author.Id}) - {message.Content}");
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error(e, "Could not process message stats"); _logger.Error("Message", "Could not process message stats", e);
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -112,12 +109,11 @@ namespace Geekbot.net
} }
} }
_userRepository.Update(user); _userRepository.Update(user);
_logger.Information( _logger.Information("Geekbot", $"{user.Username} ({user.Id}) joined {user.Guild.Name} ({user.Guild.Id})");
$"[Geekbot] {user.Id} ({user.Username}) joined {user.Guild.Id} ({user.Guild.Name})");
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error(e, "[Geekbot] Failed to send welcome message"); _logger.Error("Geekbot", "Failed to send welcome message", e);
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -145,9 +141,9 @@ namespace Geekbot.net
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error(e, "Failed to send leave message..."); _logger.Error("Geekbot", "Failed to send leave message", e);
} }
_logger.Information($"[Geekbot] {user.Id} ({user.Username}) left {user.Guild.Id} ({user.Guild.Name})"); _logger.Information("Geekbot", $"{user.Username} ({user.Id}) joined {user.Guild.Name} ({user.Guild.Id})");
} }
// //
@ -183,7 +179,7 @@ namespace Geekbot.net
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error(e, "Failed to send delete message..."); _logger.Error("Geekbot", "Failed to send delete message...", e);
} }
} }
} }

View file

@ -15,11 +15,11 @@ namespace Geekbot.net.Lib
{ {
public class ErrorHandler : IErrorHandler public class ErrorHandler : IErrorHandler
{ {
private readonly ILogger _logger; private readonly IGeekbotLogger _logger;
private readonly ITranslationHandler _translation; private readonly ITranslationHandler _translation;
private readonly IRavenClient _raven; private readonly IRavenClient _raven;
public ErrorHandler(ILogger logger, ITranslationHandler translation) public ErrorHandler(IGeekbotLogger logger, ITranslationHandler translation)
{ {
_logger = logger; _logger = logger;
_translation = translation; _translation = translation;
@ -28,7 +28,7 @@ namespace Geekbot.net.Lib
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("Geekbot", $"Command Errors will be logged to Sentry: {sentryDsn}");
} }
else else
{ {
@ -42,8 +42,7 @@ namespace Geekbot.net.Lib
{ {
var errorString = errorMessage == "def" ? _translation.GetString(Context.Guild.Id, "errorHandler", "SomethingWentWrong") : errorMessage; var errorString = errorMessage == "def" ? _translation.GetString(Context.Guild.Id, "errorHandler", "SomethingWentWrong") : errorMessage;
var errorObj = SimpleConextConverter.ConvertContext(Context); var errorObj = SimpleConextConverter.ConvertContext(Context);
var errorJson = JsonSerializer.ToJsonString(errorObj); _logger.Error("Geekbot", "An error ocured", e, errorObj);
_logger.Error(e, errorJson);
if (!string.IsNullOrEmpty(errorMessage)) if (!string.IsNullOrEmpty(errorMessage))
{ {
Context.Channel.SendMessageAsync(errorString); Context.Channel.SendMessageAsync(errorString);
@ -65,7 +64,7 @@ namespace Geekbot.net.Lib
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.Error(ex, "Errorception"); _logger.Error("Geekbot", "Errorception", ex);
} }
} }

View file

@ -10,7 +10,7 @@ namespace Geekbot.net.Lib
public GeekbotLogger() public GeekbotLogger()
{ {
JsonSerializer.SetDefaultResolver(StandardResolver.AllowPrivateExcludeNullSnakeCase); JsonSerializer.SetDefaultResolver(StandardResolver.AllowPrivateExcludeNullSnakeCase);
Info("Geekbot", "Using GeekbotLogger"); Information("Geekbot", "Using GeekbotLogger");
} }
public void Debug(string source, string message, object extra = null) public void Debug(string source, string message, object extra = null)
@ -18,14 +18,19 @@ namespace Geekbot.net.Lib
HandleLogObject("Debug", source, message, null, extra); HandleLogObject("Debug", source, message, null, extra);
} }
public void Info(string source, string message, object extra = null) public void Information(string source, string message, object extra = null)
{ {
HandleLogObject("Information", source, message, null, extra); HandleLogObject("Information", source, message, null, extra);
} }
public void Warning(string source, string message, Exception stackTrace = null, object extra = null)
{
HandleLogObject("Warning", source, message, stackTrace, extra);
}
public void Error(string source, string message, Exception stackTrace, object extra = null) public void Error(string source, string message, Exception stackTrace, object extra = null)
{ {
HandleLogObject("Debug", source, message, stackTrace, extra); HandleLogObject("Error", source, message, stackTrace, extra);
} }
private Task HandleLogObject(string type, string source, string message, Exception stackTrace = null, object extra = null) private Task HandleLogObject(string type, string source, string message, Exception stackTrace = null, object extra = null)
@ -63,7 +68,8 @@ namespace Geekbot.net.Lib
public interface IGeekbotLogger public interface IGeekbotLogger
{ {
void Debug(string source, string message, object extra = null); void Debug(string source, string message, object extra = null);
void Info(string source, string message, object extra = null); void Information(string source, string message, object extra = null);
void Warning(string source, string message, Exception stackTrace = null, object extra = null);
void Error(string source, string message, Exception stackTrace, object extra = null); void Error(string source, string message, Exception stackTrace, object extra = null);
} }
} }

View file

@ -10,12 +10,12 @@ namespace Geekbot.net.Lib
public class MalClient : IMalClient public class MalClient : IMalClient
{ {
private readonly IDatabase _redis; private readonly IDatabase _redis;
private readonly ILogger _logger; private readonly IGeekbotLogger _logger;
private ICredentialContext _credentials; private ICredentialContext _credentials;
private AnimeSearchMethodsAsync _animeSearch; private AnimeSearchMethodsAsync _animeSearch;
private MangaSearchMethodsAsync _mangaSearch; private MangaSearchMethodsAsync _mangaSearch;
public MalClient(IDatabase redis, ILogger logger) public MalClient(IDatabase redis, IGeekbotLogger logger)
{ {
_redis = redis; _redis = redis;
_logger = logger; _logger = logger;
@ -42,10 +42,10 @@ namespace Geekbot.net.Lib
} }
_animeSearch = new AnimeSearchMethodsAsync(_credentials); _animeSearch = new AnimeSearchMethodsAsync(_credentials);
_mangaSearch = new MangaSearchMethodsAsync(_credentials); _mangaSearch = new MangaSearchMethodsAsync(_credentials);
_logger.Verbose($"[Geekbot] [MalClient] Logged in to Mal"); _logger.Debug("Geekbot", "Logged in to MAL");
return true; return true;
} }
_logger.Warning("[Geekbot] [MalClient] No Credentials Set!"); _logger.Debug("Geekbot", "No MAL Credentials Set!");
return false; return false;
} }

View file

@ -10,7 +10,7 @@ namespace Geekbot.net.Lib.Media
private readonly Random rnd; private readonly Random rnd;
private readonly int totalFortunes; private readonly int totalFortunes;
public FortunesProvider(Random rnd, ILogger logger) public FortunesProvider(Random rnd, IGeekbotLogger logger)
{ {
var path = Path.GetFullPath("./Storage/fortunes"); var path = Path.GetFullPath("./Storage/fortunes");
if (File.Exists(path)) if (File.Exists(path))
@ -19,12 +19,11 @@ namespace Geekbot.net.Lib.Media
fortuneArray = rawFortunes.Split("%"); fortuneArray = rawFortunes.Split("%");
totalFortunes = fortuneArray.Length; totalFortunes = fortuneArray.Length;
this.rnd = rnd; this.rnd = rnd;
logger.Verbose($"[Geekbot] [Fortunes] Loaded {totalFortunes} Fortunes"); logger.Debug("Geekbot", "Loaded {totalFortunes} Fortunes");
} }
else else
{ {
logger.Error("Fortunes File not found"); logger.Information("Geekbot", $"Fortunes File not found at {path}");
logger.Error($"Path should be {path}");
} }
} }

View file

@ -9,7 +9,7 @@ namespace Geekbot.net.Lib.Media
public class MediaProvider : IMediaProvider public class MediaProvider : IMediaProvider
{ {
private readonly Random _random; private readonly Random _random;
private readonly ILogger _logger; private readonly IGeekbotLogger _logger;
private string[] _checkemImages; private string[] _checkemImages;
private string[] _pandaImages; private string[] _pandaImages;
private string[] _croissantImages; private string[] _croissantImages;
@ -17,61 +17,61 @@ namespace Geekbot.net.Lib.Media
private string[] _pumpkinImages; private string[] _pumpkinImages;
private string[] _turtlesImages; private string[] _turtlesImages;
public MediaProvider(Random rnd, ILogger logger) public MediaProvider(Random rnd, IGeekbotLogger logger)
{ {
_random = rnd; _random = rnd;
_logger = logger; _logger = logger;
logger.Information("[Geekbot] Loading Media Files"); logger.Information("Geekbot", "Loading Media Files");
loadCheckem(); LoadCheckem();
loadPandas(); LoadPandas();
bakeCroissants(); BakeCroissants();
loadSquirrels(); LoadSquirrels();
loadPumpkins(); LoadPumpkins();
loadTurtles(); LoadTurtles();
} }
private void loadCheckem() private void LoadCheckem()
{ {
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.Verbose($"[Geekbot] [Media] Loaded {_checkemImages.Length} CheckEm Images"); _logger.Debug("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.Verbose($"[Geekbot] [Media] Loaded {_pandaImages.Length} Panda Images"); _logger.Debug("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.Verbose($"[Geekbot] [Media] Loaded {_croissantImages.Length} Croissant Images"); _logger.Debug("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.Verbose($"[Geekbot] [Media] Loaded {_squirrelImages.Length} Squirrel Images"); _logger.Debug("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.Verbose($"[Geekbot] [Media] Loaded {_pumpkinImages.Length} Pumpkin Images"); _logger.Debug("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.Verbose($"[Geekbot] [Media] Loaded {_turtlesImages.Length} Turtle Images"); _logger.Debug("Geekbot", $"Loaded {_turtlesImages.Length} Turtle Images");
} }
public string getCheckem() public string getCheckem()

View file

@ -33,8 +33,7 @@ namespace Geekbot.net.Lib
{ {
Id = context.Channel.Id.ToString(), Id = context.Channel.Id.ToString(),
Name = context.Channel.Name Name = context.Channel.Name
}, }
TimeStamp = DateTime.Now.ToString()
}; };
} }
public static MessageDto ConvertSocketMessage(SocketMessage message) public static MessageDto ConvertSocketMessage(SocketMessage message)
@ -66,7 +65,6 @@ namespace Geekbot.net.Lib
Id = channel.Id.ToString(), Id = channel.Id.ToString(),
Name = channel.Name Name = channel.Name
}, },
TimeStamp = DateTime.Now.ToString()
}; };
} }
@ -79,7 +77,6 @@ namespace Geekbot.net.Lib
public IdAndName User { get; set; } public IdAndName User { get; set; }
public IdAndName Guild { get; set; } public IdAndName Guild { get; set; }
public IdAndName Channel { get; set; } public IdAndName Channel { get; set; }
public string TimeStamp { get; set; }
public class MessageContent public class MessageContent
{ {

View file

@ -11,17 +11,17 @@ namespace Geekbot.net.Lib
{ {
public class TranslationHandler : ITranslationHandler public class TranslationHandler : ITranslationHandler
{ {
private readonly ILogger _logger; private readonly IGeekbotLogger _logger;
private readonly IDatabase _redis; private readonly IDatabase _redis;
private Dictionary<string, Dictionary<string, Dictionary<string, string>>> _translations; private Dictionary<string, Dictionary<string, Dictionary<string, string>>> _translations;
private Dictionary<ulong, string> _serverLanguages; private Dictionary<ulong, string> _serverLanguages;
private List<string> _supportedLanguages; private List<string> _supportedLanguages;
public TranslationHandler(IReadOnlyCollection<SocketGuild> clientGuilds, IDatabase redis, ILogger logger) public TranslationHandler(IReadOnlyCollection<SocketGuild> clientGuilds, IDatabase redis, IGeekbotLogger logger)
{ {
_logger = logger; _logger = logger;
_redis = redis; _redis = redis;
_logger.Information("[Geekbot] Loading Translations"); _logger.Information("Geekbot", "Loading Translations");
LoadTranslations(); LoadTranslations();
LoadServerLanguages(clientGuilds); LoadServerLanguages(clientGuilds);
} }
@ -70,7 +70,7 @@ namespace Geekbot.net.Lib
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Fatal(e, "Failed to load Translations"); _logger.Error("Geekbot", "Failed to load Translations", e);
Environment.Exit(110); Environment.Exit(110);
} }
} }
@ -99,7 +99,7 @@ namespace Geekbot.net.Lib
translation = _translations[command][stringName]["EN"]; translation = _translations[command][stringName]["EN"];
if (string.IsNullOrWhiteSpace(translation)) if (string.IsNullOrWhiteSpace(translation))
{ {
_logger.Warning($"No translation found for {command} - {stringName}"); _logger.Warning("Geekbot", $"No translation found for {command} - {stringName}");
} }
return translation; return translation;
} }
@ -113,7 +113,7 @@ namespace Geekbot.net.Lib
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error(e, "lol nope"); _logger.Error("Geekbot", "lol nope", e);
return new Dictionary<string, string>(); return new Dictionary<string, string>();
} }
} }
@ -126,7 +126,7 @@ namespace Geekbot.net.Lib
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error(e, "lol nope"); _logger.Error("Geekbot", "lol nope", e);
return new Dictionary<string, string>(); return new Dictionary<string, string>();
} }
} }
@ -142,7 +142,7 @@ namespace Geekbot.net.Lib
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Error(e, "[Geekbot] Error while changing language"); _logger.Error("Geekbot", "Error while changing language", e);
return false; return false;
} }
} }

View file

@ -13,8 +13,8 @@ namespace Geekbot.net.Lib
public class UserRepository : IUserRepository public class UserRepository : IUserRepository
{ {
private readonly IDatabase _redis; private readonly IDatabase _redis;
private readonly ILogger _logger; private readonly IGeekbotLogger _logger;
public UserRepository(IDatabase redis, ILogger logger) public UserRepository(IDatabase redis, IGeekbotLogger logger)
{ {
_redis = redis; _redis = redis;
_logger = logger; _logger = logger;
@ -38,12 +38,12 @@ namespace Geekbot.net.Lib
} }
Store(savedUser); Store(savedUser);
_logger.Information($"[UserRepository] Updated User {user.Username}#{user.Discriminator} ({user.Id})"); _logger.Information("UserRepository", "Updated User", savedUser);
return Task.FromResult(true); return Task.FromResult(true);
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Warning(e, $"[UserRepository] Failed to update {user.Username}#{user.Discriminator} ({user.Id})"); _logger.Warning("UserRepository", $"Failed to update user: {user.Username}#{user.Discriminator} ({user.Id})", e);
return Task.FromResult(false); return Task.FromResult(false);
} }
} }
@ -105,7 +105,7 @@ namespace Geekbot.net.Lib
} }
catch (Exception e) catch (Exception e)
{ {
_logger.Warning(e, $"[UserRepository] Failed to get {userId} from repository"); _logger.Warning("UserRepository", "Failed to get {userId} from repository", e);
return new UserRepositoryUser(); return new UserRepositoryUser();
} }
} }

View file

@ -27,8 +27,7 @@ namespace Geekbot.net
private IServiceCollection services; private IServiceCollection services;
private IServiceProvider servicesProvider; private IServiceProvider servicesProvider;
private RedisValue token; private RedisValue token;
private ILogger logger; private IGeekbotLogger logger;
private IGeekbotLogger gLogger;
private IUserRepository userRepository; private IUserRepository userRepository;
private string[] args; private string[] args;
private bool firstStart = false; private bool firstStart = false;
@ -43,26 +42,23 @@ namespace Geekbot.net
logo.AppendLine(@" \____|_____|_____|_|\_\____/ \___/ |_|"); logo.AppendLine(@" \____|_____|_____|_|\_\____/ \___/ |_|");
logo.AppendLine("========================================="); logo.AppendLine("=========================================");
Console.WriteLine(logo.ToString()); Console.WriteLine(logo.ToString());
var logger = LoggerFactory.createLogger(args); var logger = new GeekbotLogger();
var gLogger = new GeekbotLogger(); logger.Information("Geekbot", "Starting...");
logger.Information("[Geekbot] Starting...");
try try
{ {
new Program().MainAsync(args, logger, gLogger).GetAwaiter().GetResult(); new Program().MainAsync(args, logger).GetAwaiter().GetResult();
} }
catch (Exception e) catch (Exception e)
{ {
logger.Fatal(e, "[Geekbot] RIP"); logger.Error("Geekbot", "RIP", e);
} }
} }
private async Task MainAsync(string[] args, ILogger logger, IGeekbotLogger gLogger) private async Task MainAsync(string[] args, IGeekbotLogger logger)
{ {
this.logger = logger; this.logger = logger;
this.gLogger = gLogger;
this.args = args; this.args = args;
logger.Information("[Geekbot] Initing Stuff"); logger.Information("Geekbot", "Initing Stuff");
gLogger.Info("Geekbot", "Initing Stuff");
client = new DiscordSocketClient(new DiscordSocketConfig client = new DiscordSocketClient(new DiscordSocketConfig
{ {
@ -76,11 +72,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("Redis", $"Connected to db {redis.Database}");
} }
catch (Exception e) catch (Exception e)
{ {
logger.Fatal(e, "[Redis] Redis Connection Failed"); logger.Error("Redis", "Redis Connection Failed", e);
Environment.Exit(102); Environment.Exit(102);
} }
@ -107,7 +103,7 @@ namespace Geekbot.net
var audioUtils = new AudioUtils(); var audioUtils = new AudioUtils();
services.AddSingleton(redis); services.AddSingleton(redis);
services.AddSingleton<ILogger>(logger); services.AddSingleton<IGeekbotLogger>(logger);
services.AddSingleton<IUserRepository>(userRepository); services.AddSingleton<IUserRepository>(userRepository);
services.AddSingleton<ILevelCalc>(levelCalc); services.AddSingleton<ILevelCalc>(levelCalc);
services.AddSingleton<IEmojiConverter>(emojiConverter); services.AddSingleton<IEmojiConverter>(emojiConverter);
@ -117,7 +113,7 @@ namespace Geekbot.net
services.AddSingleton<IMediaProvider>(mediaProvider); services.AddSingleton<IMediaProvider>(mediaProvider);
services.AddSingleton<IMalClient>(malClient); services.AddSingleton<IMalClient>(malClient);
logger.Information("[Geekbot] Connecting to Discord"); logger.Information("Geekbot", "Connecting to Discord");
await Login(); await Login();
@ -134,9 +130,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("Geekbot", $"Now Connected as {client.CurrentUser.Username} to {client.Guilds.Count} Servers");
logger.Information("[Geekbot] Registering Stuff"); logger.Information("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); var errorHandler = new ErrorHandler(logger, translationHandler);
await commands.AddModulesAsync(Assembly.GetEntryAssembly()); await commands.AddModulesAsync(Assembly.GetEntryAssembly());
@ -146,7 +142,7 @@ namespace Geekbot.net
services.AddSingleton<DiscordSocketClient>(client); services.AddSingleton<DiscordSocketClient>(client);
servicesProvider = services.BuildServiceProvider(); servicesProvider = services.BuildServiceProvider();
var handlers = new Handlers(client, logger, redis, servicesProvider, commands, userRepository, gLogger); var handlers = new Handlers(client, logger, redis, servicesProvider, commands, userRepository);
client.MessageReceived += handlers.RunCommand; client.MessageReceived += handlers.RunCommand;
client.MessageReceived += handlers.UpdateStats; client.MessageReceived += handlers.UpdateStats;
@ -157,21 +153,21 @@ namespace Geekbot.net
if (firstStart || args.Contains("--reset")) if (firstStart || args.Contains("--reset"))
{ {
logger.Information("[Geekbot] Finishing setup"); logger.Information("Geekbot", "Finishing setup");
await FinishSetup(); await FinishSetup();
logger.Information("[Geekbot] Setup finished"); logger.Information("Geekbot", "Setup finished");
} }
if (!args.Contains("--disable-api")) if (!args.Contains("--disable-api"))
{ {
startWebApi(); startWebApi();
} }
logger.Information("[Geekbot] Done and ready for use\n"); logger.Information("Geekbot", "Done and ready for use");
} }
} }
catch (Exception e) catch (Exception e)
{ {
logger.Fatal(e, "Could not connect to discord..."); logger.Error("Discord", "Could not connect...", e);
Environment.Exit(103); Environment.Exit(103);
} }
} }
@ -185,16 +181,16 @@ namespace Geekbot.net
private void startWebApi() private void startWebApi()
{ {
logger.Information("[API] Starting Webserver"); logger.Information("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("API", $"Webserver now running on {webApiUrl}");
} }
private async Task<Task> FinishSetup() private async Task<Task> FinishSetup()
{ {
var appInfo = await client.GetApplicationInfoAsync(); var appInfo = await client.GetApplicationInfoAsync();
logger.Information($"[Setup] Just a moment while i setup everything {appInfo.Owner.Username}"); logger.Information("Setup", $"Just a moment while i setup everything {appInfo.Owner.Username}");
try try
{ {
redis.StringSet("botOwner", appInfo.Owner.Id); redis.StringSet("botOwner", appInfo.Owner.Id);
@ -207,12 +203,11 @@ namespace Geekbot.net
User.Username = appInfo.Name.ToString(); User.Username = appInfo.Name.ToString();
}); });
} }
logger.Information($"[Setup] Everything done, enjoy!"); logger.Information("Setup", "Everything done, enjoy!");
} }
catch (Exception e) catch (Exception e)
{ {
logger.Warning(e, "[Setup] Oha, it seems like something went wrong while running the setup"); logger.Warning("Setup", "Oha, it seems like something went wrong while running the setup, geekbot will work never the less though", e);
logger.Warning("[Setup] Geekbot will work never the less, some features might be disabled though");
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -223,22 +218,20 @@ namespace Geekbot.net
switch (message.Severity) switch (message.Severity)
{ {
case LogSeverity.Verbose: case LogSeverity.Verbose:
logger.Verbose(logMessage);
break;
case LogSeverity.Debug: case LogSeverity.Debug:
logger.Debug(logMessage); logger.Debug(message.Source, message.Message);
break; break;
case LogSeverity.Info: case LogSeverity.Info:
logger.Information(logMessage); logger.Information(message.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.Exception, logMessage); logger.Error(message.Source, message.Message, message.Exception);
break; break;
default: default:
logger.Information($"{logMessage} --- {message.Severity}"); logger.Information(message.Source, $"{logMessage} --- {message.Severity}");
break; break;
} }
return Task.CompletedTask; return Task.CompletedTask;