-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStructLog.cs
More file actions
55 lines (44 loc) · 2.04 KB
/
StructLog.cs
File metadata and controls
55 lines (44 loc) · 2.04 KB
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
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StructLog.Interfaces;
using StructLog.Models;
using System.Text.Json;
namespace StructLog
{
public class StructLog<T>(
ILogger<T> logger,
IOptions<StructLogOptions> options,
IEnumerable<ILogEnricher> enrichers) : IStructLog<T> where T : class
{
private readonly ILogger<T> _logger = logger;
private readonly StructLogOptions _options = options.Value;
private readonly IEnumerable<ILogEnricher> _enrichers = enrichers;
public IDisposable BeginScope(IDictionary<string, object> context)
=> _logger.BeginScope(context);
public void Error(string message, IEventCode eventCode, Exception? ex = null, object? data = null)
=> Log(LogLevel.Error, message, eventCode, ex, data);
public void Info(string message, IEventCode eventCode, object? data = null)
=> Log(LogLevel.Information, message, eventCode, null, data);
public void Warning(string message, IEventCode eventCode, object? data = null)
=> Log(LogLevel.Warning, message, eventCode, null, data);
record LogJsonState(string Json);
private void Log(LogLevel level, string message, IEventCode eventCode, Exception? exception, object? data)
{
var contextData = new Dictionary<string, object>();
if (_options.EnableEnrichers)
foreach (var enricher in _enrichers)
enricher.Enrich(contextData);
var logEntry = new
{
EventCode = eventCode.Code,
EventDescription = eventCode.Description,
Message = message,
Context = contextData,
Data = data
};
string json = JsonSerializer.Serialize(logEntry, new JsonSerializerOptions { WriteIndented = true });
using (_logger.BeginScope(contextData))
_logger.Log(level, default, (object)null, exception, (_, __) => json);
}
}
}