2024-11-17 22:51:54 +01:00
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
|
|
namespace DotBased.Logging.MEL;
|
|
|
|
|
|
|
|
public class BasedLogger : Microsoft.Extensions.Logging.ILogger
|
|
|
|
{
|
2024-11-30 18:55:09 +01:00
|
|
|
private const string _messageTemplateKey = "{OriginalFormat}";
|
2024-11-17 22:51:54 +01:00
|
|
|
public BasedLogger(ILogger logger)
|
|
|
|
{
|
|
|
|
basedLogger = logger;
|
|
|
|
}
|
|
|
|
|
|
|
|
private readonly ILogger basedLogger;
|
|
|
|
|
|
|
|
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
|
|
|
{
|
|
|
|
if (!IsEnabled(logLevel))
|
|
|
|
return;
|
|
|
|
var severity = ConvertLogLevelToSeverity(logLevel);
|
|
|
|
var capsule = ConstructCapsule(severity, eventId, state, exception, formatter);
|
|
|
|
basedLogger.Log(capsule);
|
|
|
|
}
|
|
|
|
|
|
|
|
private LogCapsule ConstructCapsule<TState>(LogSeverity severity, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
|
|
|
{
|
2024-11-25 18:11:22 +01:00
|
|
|
var msgTemplate = string.Empty;
|
2024-11-30 18:55:09 +01:00
|
|
|
List<object?> templateParams = [];
|
2024-11-17 22:51:54 +01:00
|
|
|
if (state is IEnumerable<KeyValuePair<string, object>> stateEnum)
|
|
|
|
{
|
|
|
|
foreach (var prop in stateEnum)
|
|
|
|
{
|
2024-11-30 18:55:09 +01:00
|
|
|
if (prop is { Key: _messageTemplateKey, Value: string propValueString })
|
2024-11-25 18:11:22 +01:00
|
|
|
{
|
|
|
|
msgTemplate = propValueString;
|
2024-11-30 18:55:09 +01:00
|
|
|
continue;
|
2024-11-25 18:11:22 +01:00
|
|
|
}
|
2024-11-30 18:55:09 +01:00
|
|
|
templateParams.Add(prop.Value);
|
2024-11-17 22:51:54 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return new LogCapsule()
|
|
|
|
{
|
|
|
|
Exception = exception,
|
2024-11-30 18:55:09 +01:00
|
|
|
Message = msgTemplate,
|
|
|
|
Parameters = templateParams.ToArray(),
|
2024-11-17 22:51:54 +01:00
|
|
|
Severity = severity,
|
|
|
|
TimeStamp = DateTime.Now,
|
|
|
|
Logger = basedLogger as LoggerBase ?? throw new NullReferenceException(nameof(basedLogger))
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
private LogSeverity ConvertLogLevelToSeverity(LogLevel level)
|
|
|
|
{
|
|
|
|
return level switch
|
|
|
|
{
|
|
|
|
LogLevel.Trace => LogSeverity.Trace,
|
|
|
|
LogLevel.Debug => LogSeverity.Debug,
|
|
|
|
LogLevel.Information => LogSeverity.Info,
|
|
|
|
LogLevel.Warning => LogSeverity.Warning,
|
|
|
|
LogLevel.Error => LogSeverity.Error,
|
|
|
|
LogLevel.Critical => LogSeverity.Fatal,
|
|
|
|
LogLevel.None => LogSeverity.Ignore,
|
|
|
|
_ => LogSeverity.Verbose
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;
|
|
|
|
|
|
|
|
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => default;
|
|
|
|
}
|