|
9 | 9 | using Serilog.Debugging;
|
10 | 10 | using System.Collections.Concurrent;
|
11 | 11 |
|
12 |
| -namespace Serilog.Extensions.Logging |
| 12 | +namespace Serilog.Extensions.Logging; |
| 13 | + |
| 14 | +class SerilogLogger : FrameworkLogger |
13 | 15 | {
|
14 |
| - class SerilogLogger : FrameworkLogger |
15 |
| - { |
16 |
| - internal static readonly ConcurrentDictionary<string, string> DestructureDictionary = new ConcurrentDictionary<string, string>(); |
17 |
| - internal static readonly ConcurrentDictionary<string, string> StringifyDictionary = new ConcurrentDictionary<string, string>(); |
| 16 | + internal static readonly ConcurrentDictionary<string, string> DestructureDictionary = new ConcurrentDictionary<string, string>(); |
| 17 | + internal static readonly ConcurrentDictionary<string, string> StringifyDictionary = new ConcurrentDictionary<string, string>(); |
18 | 18 |
|
19 |
| - readonly SerilogLoggerProvider _provider; |
20 |
| - readonly ILogger _logger; |
| 19 | + readonly SerilogLoggerProvider _provider; |
| 20 | + readonly ILogger _logger; |
21 | 21 |
|
22 |
| - static readonly CachingMessageTemplateParser MessageTemplateParser = new(); |
| 22 | + static readonly CachingMessageTemplateParser MessageTemplateParser = new(); |
23 | 23 |
|
24 |
| - // It's rare to see large event ids, as they are category-specific |
25 |
| - static readonly LogEventProperty[] LowEventIdValues = Enumerable.Range(0, 48) |
26 |
| - .Select(n => new LogEventProperty("Id", new ScalarValue(n))) |
27 |
| - .ToArray(); |
| 24 | + // It's rare to see large event ids, as they are category-specific |
| 25 | + static readonly LogEventProperty[] LowEventIdValues = Enumerable.Range(0, 48) |
| 26 | + .Select(n => new LogEventProperty("Id", new ScalarValue(n))) |
| 27 | + .ToArray(); |
28 | 28 |
|
29 |
| - public SerilogLogger( |
30 |
| - SerilogLoggerProvider provider, |
31 |
| - ILogger? logger = null, |
32 |
| - string? name = null) |
33 |
| - { |
34 |
| - _provider = provider ?? throw new ArgumentNullException(nameof(provider)); |
35 |
| - _logger = logger!; |
| 29 | + public SerilogLogger( |
| 30 | + SerilogLoggerProvider provider, |
| 31 | + ILogger? logger = null, |
| 32 | + string? name = null) |
| 33 | + { |
| 34 | + _provider = provider ?? throw new ArgumentNullException(nameof(provider)); |
| 35 | + _logger = logger!; |
36 | 36 |
|
37 |
| - // If a logger was passed, the provider has already added itself as an enricher |
38 |
| - _logger ??= Serilog.Log.Logger.ForContext(new[] { provider }); |
| 37 | + // If a logger was passed, the provider has already added itself as an enricher |
| 38 | + _logger ??= Serilog.Log.Logger.ForContext(new[] { provider }); |
39 | 39 |
|
40 |
| - if (name != null) |
41 |
| - { |
42 |
| - _logger = _logger.ForContext(Constants.SourceContextPropertyName, name); |
43 |
| - } |
| 40 | + if (name != null) |
| 41 | + { |
| 42 | + _logger = _logger.ForContext(Constants.SourceContextPropertyName, name); |
44 | 43 | }
|
| 44 | + } |
45 | 45 |
|
46 |
| - public bool IsEnabled(LogLevel logLevel) |
| 46 | + public bool IsEnabled(LogLevel logLevel) |
| 47 | + { |
| 48 | + return logLevel != LogLevel.None && _logger.IsEnabled(LevelConvert.ToSerilogLevel(logLevel)); |
| 49 | + } |
| 50 | + |
| 51 | + public IDisposable BeginScope<TState>(TState state) |
| 52 | + { |
| 53 | + return _provider.BeginScope(state); |
| 54 | + } |
| 55 | + |
| 56 | + public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) |
| 57 | + { |
| 58 | + if (logLevel == LogLevel.None) |
47 | 59 | {
|
48 |
| - return logLevel != LogLevel.None && _logger.IsEnabled(LevelConvert.ToSerilogLevel(logLevel)); |
| 60 | + return; |
49 | 61 | }
|
50 |
| - |
51 |
| - public IDisposable BeginScope<TState>(TState state) |
| 62 | + var level = LevelConvert.ToSerilogLevel(logLevel); |
| 63 | + if (!_logger.IsEnabled(level)) |
52 | 64 | {
|
53 |
| - return _provider.BeginScope(state); |
| 65 | + return; |
54 | 66 | }
|
55 | 67 |
|
56 |
| - public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) |
| 68 | + try |
57 | 69 | {
|
58 |
| - if (logLevel == LogLevel.None) |
59 |
| - { |
60 |
| - return; |
61 |
| - } |
62 |
| - var level = LevelConvert.ToSerilogLevel(logLevel); |
63 |
| - if (!_logger.IsEnabled(level)) |
64 |
| - { |
65 |
| - return; |
66 |
| - } |
67 |
| - |
68 |
| - try |
69 |
| - { |
70 |
| - Write(level, eventId, state, exception, formatter); |
71 |
| - } |
72 |
| - catch (Exception ex) |
73 |
| - { |
74 |
| - SelfLog.WriteLine($"Failed to write event through {typeof(SerilogLogger).Name}: {ex}"); |
75 |
| - } |
| 70 | + Write(level, eventId, state, exception, formatter); |
76 | 71 | }
|
77 |
| - |
78 |
| - void Write<TState>(LogEventLevel level, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) |
| 72 | + catch (Exception ex) |
79 | 73 | {
|
80 |
| - var logger = _logger; |
81 |
| - string? messageTemplate = null; |
| 74 | + SelfLog.WriteLine($"Failed to write event through {typeof(SerilogLogger).Name}: {ex}"); |
| 75 | + } |
| 76 | + } |
82 | 77 |
|
83 |
| - var properties = new List<LogEventProperty>(); |
| 78 | + void Write<TState>(LogEventLevel level, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) |
| 79 | + { |
| 80 | + var logger = _logger; |
| 81 | + string? messageTemplate = null; |
84 | 82 |
|
85 |
| - if (state is IEnumerable<KeyValuePair<string, object>> structure) |
86 |
| - { |
87 |
| - foreach (var property in structure) |
88 |
| - { |
89 |
| - if (property.Key == SerilogLoggerProvider.OriginalFormatPropertyName && property.Value is string value) |
90 |
| - { |
91 |
| - messageTemplate = value; |
92 |
| - } |
93 |
| - else if (property.Key.StartsWith("@")) |
94 |
| - { |
95 |
| - if (logger.BindProperty(DestructureDictionary.GetOrAdd(property.Key, k => k.Substring(1)), property.Value, true, out var destructured)) |
96 |
| - properties.Add(destructured); |
97 |
| - } |
98 |
| - else if (property.Key.StartsWith("$")) |
99 |
| - { |
100 |
| - if (logger.BindProperty(StringifyDictionary.GetOrAdd(property.Key, k => k.Substring(1)), property.Value?.ToString(), true, out var stringified)) |
101 |
| - properties.Add(stringified); |
102 |
| - } |
103 |
| - else |
104 |
| - { |
105 |
| - if (logger.BindProperty(property.Key, property.Value, false, out var bound)) |
106 |
| - properties.Add(bound); |
107 |
| - } |
108 |
| - } |
| 83 | + var properties = new List<LogEventProperty>(); |
109 | 84 |
|
110 |
| - var stateType = state.GetType(); |
111 |
| - var stateTypeInfo = stateType.GetTypeInfo(); |
112 |
| - // Imperfect, but at least eliminates `1 names |
113 |
| - if (messageTemplate == null && !stateTypeInfo.IsGenericType) |
| 85 | + if (state is IEnumerable<KeyValuePair<string, object>> structure) |
| 86 | + { |
| 87 | + foreach (var property in structure) |
| 88 | + { |
| 89 | + if (property.Key == SerilogLoggerProvider.OriginalFormatPropertyName && property.Value is string value) |
114 | 90 | {
|
115 |
| - messageTemplate = "{" + stateType.Name + ":l}"; |
116 |
| - if (logger.BindProperty(stateType.Name, AsLoggableValue(state, formatter), false, out var stateTypeProperty)) |
117 |
| - properties.Add(stateTypeProperty); |
| 91 | + messageTemplate = value; |
118 | 92 | }
|
119 |
| - } |
120 |
| - |
121 |
| - if (messageTemplate == null) |
122 |
| - { |
123 |
| - string? propertyName = null; |
124 |
| - if (state != null) |
| 93 | + else if (property.Key.StartsWith("@")) |
125 | 94 | {
|
126 |
| - propertyName = "State"; |
127 |
| - messageTemplate = "{State:l}"; |
| 95 | + if (logger.BindProperty(DestructureDictionary.GetOrAdd(property.Key, k => k.Substring(1)), property.Value, true, out var destructured)) |
| 96 | + properties.Add(destructured); |
128 | 97 | }
|
129 |
| - else if (formatter != null) |
| 98 | + else if (property.Key.StartsWith("$")) |
130 | 99 | {
|
131 |
| - propertyName = "Message"; |
132 |
| - messageTemplate = "{Message:l}"; |
| 100 | + if (logger.BindProperty(StringifyDictionary.GetOrAdd(property.Key, k => k.Substring(1)), property.Value?.ToString(), true, out var stringified)) |
| 101 | + properties.Add(stringified); |
133 | 102 | }
|
134 |
| - |
135 |
| - if (propertyName != null) |
| 103 | + else |
136 | 104 | {
|
137 |
| - if (logger.BindProperty(propertyName, AsLoggableValue(state, formatter!), false, out var property)) |
138 |
| - properties.Add(property); |
| 105 | + if (logger.BindProperty(property.Key, property.Value, false, out var bound)) |
| 106 | + properties.Add(bound); |
139 | 107 | }
|
140 | 108 | }
|
141 | 109 |
|
142 |
| - if (eventId.Id != 0 || eventId.Name != null) |
143 |
| - properties.Add(CreateEventIdProperty(eventId)); |
144 |
| - |
145 |
| - var parsedTemplate = MessageTemplateParser.Parse(messageTemplate ?? ""); |
146 |
| - var evt = new LogEvent(DateTimeOffset.Now, level, exception, parsedTemplate, properties); |
147 |
| - logger.Write(evt); |
148 |
| - } |
149 |
| - |
150 |
| - static object? AsLoggableValue<TState>(TState state, Func<TState, Exception, string> formatter) |
151 |
| - { |
152 |
| - object? sobj = state; |
153 |
| - if (formatter != null) |
154 |
| - sobj = formatter(state, null!); |
155 |
| - return sobj; |
| 110 | + var stateType = state.GetType(); |
| 111 | + var stateTypeInfo = stateType.GetTypeInfo(); |
| 112 | + // Imperfect, but at least eliminates `1 names |
| 113 | + if (messageTemplate == null && !stateTypeInfo.IsGenericType) |
| 114 | + { |
| 115 | + messageTemplate = "{" + stateType.Name + ":l}"; |
| 116 | + if (logger.BindProperty(stateType.Name, AsLoggableValue(state, formatter), false, out var stateTypeProperty)) |
| 117 | + properties.Add(stateTypeProperty); |
| 118 | + } |
156 | 119 | }
|
157 | 120 |
|
158 |
| - internal static LogEventProperty CreateEventIdProperty(EventId eventId) |
| 121 | + if (messageTemplate == null) |
159 | 122 | {
|
160 |
| - var properties = new List<LogEventProperty>(2); |
161 |
| - |
162 |
| - if (eventId.Id != 0) |
| 123 | + string? propertyName = null; |
| 124 | + if (state != null) |
163 | 125 | {
|
164 |
| - if (eventId.Id >= 0 && eventId.Id < LowEventIdValues.Length) |
165 |
| - // Avoid some allocations |
166 |
| - properties.Add(LowEventIdValues[eventId.Id]); |
167 |
| - else |
168 |
| - properties.Add(new LogEventProperty("Id", new ScalarValue(eventId.Id))); |
| 126 | + propertyName = "State"; |
| 127 | + messageTemplate = "{State:l}"; |
| 128 | + } |
| 129 | + else if (formatter != null) |
| 130 | + { |
| 131 | + propertyName = "Message"; |
| 132 | + messageTemplate = "{Message:l}"; |
169 | 133 | }
|
170 | 134 |
|
171 |
| - if (eventId.Name != null) |
| 135 | + if (propertyName != null) |
172 | 136 | {
|
173 |
| - properties.Add(new LogEventProperty("Name", new ScalarValue(eventId.Name))); |
| 137 | + if (logger.BindProperty(propertyName, AsLoggableValue(state, formatter!), false, out var property)) |
| 138 | + properties.Add(property); |
174 | 139 | }
|
| 140 | + } |
| 141 | + |
| 142 | + if (eventId.Id != 0 || eventId.Name != null) |
| 143 | + properties.Add(CreateEventIdProperty(eventId)); |
| 144 | + |
| 145 | + var parsedTemplate = MessageTemplateParser.Parse(messageTemplate ?? ""); |
| 146 | + var evt = new LogEvent(DateTimeOffset.Now, level, exception, parsedTemplate, properties); |
| 147 | + logger.Write(evt); |
| 148 | + } |
| 149 | + |
| 150 | + static object? AsLoggableValue<TState>(TState state, Func<TState, Exception, string> formatter) |
| 151 | + { |
| 152 | + object? sobj = state; |
| 153 | + if (formatter != null) |
| 154 | + sobj = formatter(state, null!); |
| 155 | + return sobj; |
| 156 | + } |
175 | 157 |
|
176 |
| - return new LogEventProperty("EventId", new StructureValue(properties)); |
| 158 | + internal static LogEventProperty CreateEventIdProperty(EventId eventId) |
| 159 | + { |
| 160 | + var properties = new List<LogEventProperty>(2); |
| 161 | + |
| 162 | + if (eventId.Id != 0) |
| 163 | + { |
| 164 | + if (eventId.Id >= 0 && eventId.Id < LowEventIdValues.Length) |
| 165 | + // Avoid some allocations |
| 166 | + properties.Add(LowEventIdValues[eventId.Id]); |
| 167 | + else |
| 168 | + properties.Add(new LogEventProperty("Id", new ScalarValue(eventId.Id))); |
177 | 169 | }
|
| 170 | + |
| 171 | + if (eventId.Name != null) |
| 172 | + { |
| 173 | + properties.Add(new LogEventProperty("Name", new ScalarValue(eventId.Name))); |
| 174 | + } |
| 175 | + |
| 176 | + return new LogEventProperty("EventId", new StructureValue(properties)); |
178 | 177 | }
|
179 | 178 | }
|
0 commit comments