geekbot/Geekbot.net/Lib/Logger/GeekbotLogger.cs

71 lines
2.8 KiB
C#
Raw Normal View History

2017-12-29 01:00:31 +01:00
using System;
2018-05-01 02:31:54 +02:00
using Newtonsoft.Json;
2017-12-29 01:00:31 +01:00
namespace Geekbot.net.Lib.Logger
2017-12-29 01:00:31 +01:00
{
public class GeekbotLogger : IGeekbotLogger
{
2018-05-02 23:32:40 +02:00
private readonly bool _logAsJson;
2018-05-01 22:55:47 +02:00
private readonly NLog.Logger _logger;
2018-05-01 16:50:48 +02:00
private readonly JsonSerializerSettings _serializerSettings;
2018-05-02 20:19:11 +02:00
public GeekbotLogger(RunParameters runParameters, bool sumologicActive)
2017-12-29 01:00:31 +01:00
{
2018-05-02 23:32:40 +02:00
_logAsJson = sumologicActive || runParameters.LogJson;
2018-05-02 20:19:11 +02:00
_logger = LoggerFactory.CreateNLog(runParameters, sumologicActive);
2018-05-01 16:50:48 +02:00
_serializerSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
NullValueHandling = NullValueHandling.Include
};
Information("Geekbot", "Using GeekbotLogger");
2017-12-29 01:00:31 +01:00
}
public void Trace(string source, string message, object extra = null)
{
2018-05-03 21:20:49 +02:00
_logger.Trace(CreateLogString("Trace", source, message, null, extra));
}
2017-12-29 01:00:31 +01:00
public void Debug(string source, string message, object extra = null)
{
2018-05-01 22:55:47 +02:00
_logger.Debug(CreateLogString("Debug", source, message, null, extra));
2017-12-29 01:00:31 +01:00
}
public void Information(string source, string message, object extra = null)
2017-12-29 01:00:31 +01:00
{
2018-05-01 22:55:47 +02:00
_logger.Info(CreateLogString("Information", source, message, null, extra));
2017-12-29 01:00:31 +01:00
}
public void Warning(string source, string message, Exception stackTrace = null, object extra = null)
{
2018-05-01 22:55:47 +02:00
_logger.Warn(CreateLogString("Warning", source, message, stackTrace, extra));
}
2017-12-29 01:00:31 +01:00
public void Error(string source, string message, Exception stackTrace, object extra = null)
{
2018-05-01 22:55:47 +02:00
_logger.Error(stackTrace, CreateLogString("Error", source, message, stackTrace, extra));
2017-12-29 01:00:31 +01:00
}
private string CreateLogString(string type, string source, string message, Exception stackTrace = null, object extra = null)
2017-12-29 01:00:31 +01:00
{
2018-05-02 23:32:40 +02:00
if (_logAsJson)
2017-12-29 01:00:31 +01:00
{
var logObject = new GeekbotLoggerObject
{
Timestamp = DateTime.Now,
Type = type,
Source = source,
Message = message,
StackTrace = stackTrace,
Extra = extra
};
return JsonConvert.SerializeObject(logObject, Formatting.None, _serializerSettings);
}
if (source != "Message") return $"[{source}] - {message}";
var m = (MessageDto) extra;
2018-05-03 21:20:49 +02:00
return $"[{source}] - [{m?.Guild.Name} - {m?.Channel.Name}] {m?.User.Name}: {m?.Message.Content}";
2017-12-29 01:00:31 +01:00
}
}
}