-
Notifications
You must be signed in to change notification settings - Fork 0
/
RabbitMQLoggerProvider.cs
80 lines (68 loc) · 2.28 KB
/
RabbitMQLoggerProvider.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using Net6_Demo.Helpers;
using System.Collections.Concurrent;
namespace Net6_Demo.Providers
{
public sealed class RabbitMQLoggerProvider : ILoggerProvider
{
private readonly RabbitMQHelper _rabbit;
private readonly ConcurrentDictionary<string, RabbitMQLogger> _loggers = new();
public RabbitMQLoggerProvider(RabbitMQHelper rabbit)
{
_rabbit = rabbit;
}
public ILogger CreateLogger(string categoryName) => _loggers.GetOrAdd(categoryName, name => new RabbitMQLogger(name, _rabbit));
public void Dispose()
{
_loggers.Clear();
}
}
//I am lazy so put together
public class RabbitMQLogger : ILogger
{
private readonly string _name;
private readonly RabbitMQHelper _rabbit;
public RabbitMQLogger(string name, RabbitMQHelper rabbit) => (_name, _rabbit) = (name, rabbit);
public IDisposable BeginScope<TState>(TState state) => default;
public bool IsEnabled(LogLevel level)
{
switch (level)
{
case LogLevel.Trace:
case LogLevel.None:
case LogLevel.Debug:
return false;
default:
return true;
}
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
var log = new LogObject
{
LogLevel = logLevel,
EventId = eventId.Id,
Module = _name,
LogData = formatter(state, exception)
};
if (exception != null)
{
log.ErrorCode = exception.HResult;
log.ErrorMessage = exception.Message;
}
_rabbit.Publish(log);
}
}
public class LogObject
{
public int EventId { get; set; }
public LogLevel LogLevel { get; set; }
public int ErrorCode { get; set; }
public string? ErrorMessage { get; set; }
public string LogData { get; set; } = null!;
public string Module { get; set; } = null!;
}
}