-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathSerilogInput.cs
231 lines (196 loc) · 9.18 KB
/
SerilogInput.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Validation;
using Serilog.Core;
using Serilog.Events;
using Microsoft.Diagnostics.EventFlow.Metadata;
using Microsoft.Diagnostics.EventFlow.Configuration;
namespace Microsoft.Diagnostics.EventFlow.Inputs
{
/// <summary>
/// An input that supplies events from the Serilog structured logging library.
/// </summary>
public class SerilogInput : ILogEventSink, IObservable<EventData>, IDisposable
{
private static readonly IDictionary<LogEventLevel, LogLevel> ToLogLevel =
new Dictionary<LogEventLevel, LogLevel>
{
[LogEventLevel.Verbose] = LogLevel.Verbose,
[LogEventLevel.Debug] = LogLevel.Verbose,
[LogEventLevel.Information] = LogLevel.Informational,
[LogEventLevel.Warning] = LogLevel.Warning,
[LogEventLevel.Error] = LogLevel.Error,
[LogEventLevel.Fatal] = LogLevel.Critical
};
private EventFlowSubject<EventData> subject;
private IHealthReporter healthReporter;
internal SerilogInputConfiguration inputConfiguration;
private Func<LogEventPropertyValue, object> valueSerializer;
/// <summary>
/// Creates an instance of <see cref="SerilogInput"/> using default values
/// </summary>
/// <param name="healthReporter">A health reporter through which the input can report errors.</param>
public SerilogInput(IHealthReporter healthReporter) : this(new SerilogInputConfiguration(), healthReporter) { }
/// <summary>
/// Construct a <see cref="SerilogInput"/>.
/// </summary>
/// <param name="configuration">A configuration to be used to configure the input</param>
/// <param name="healthReporter">A health reporter through which the input can report errors.</param>
public SerilogInput(IConfiguration configuration, IHealthReporter healthReporter)
{
Requires.NotNull(configuration, nameof(configuration));
Requires.NotNull(healthReporter, nameof(healthReporter));
var inputConfiguration = new SerilogInputConfiguration();
try
{
configuration.Bind(inputConfiguration);
}
catch
{
healthReporter.ReportProblem($"Invalid {nameof(SerilogInputConfiguration)} configuration encountered: '{configuration}'",
EventFlowContextIdentifiers.Configuration);
throw;
}
Initialize(inputConfiguration, healthReporter);
}
/// <summary>
/// Creates an instance of <see cref="SerilogInput"/>
/// </summary>
/// <param name="inputConfiguration">A configuration to be used to configure the input</param>
/// <param name="healthReporter">A health reporter through which the input can report errors.</param>
public SerilogInput(SerilogInputConfiguration inputConfiguration, IHealthReporter healthReporter)
{
Requires.NotNull(inputConfiguration, nameof(inputConfiguration));
Requires.NotNull(healthReporter, nameof(healthReporter));
Initialize(inputConfiguration, healthReporter);
}
private void Initialize(SerilogInputConfiguration inputConfiguration, IHealthReporter healthReporter)
{
this.healthReporter = healthReporter;
this.inputConfiguration = inputConfiguration;
this.subject = new EventFlowSubject<EventData>();
this.valueSerializer = this.inputConfiguration.UseSerilogDepthLevel ? (Func<LogEventPropertyValue, object>)this.ToRawValue : this.ToRawScalar;
}
void ILogEventSink.Emit(LogEvent logEvent)
{
if (logEvent == null)
{
return;
}
EventData e = ToEventData(logEvent);
this.subject.OnNext(e);
}
/// <inheritdoc/>
public IDisposable Subscribe(IObserver<EventData> observer)
{
return this.subject.Subscribe(observer);
}
/// <inheritdoc/>
public virtual void Dispose()
{
this.subject.Dispose();
}
private EventData ToEventData(LogEvent logEvent)
{
EventData eventData = new EventData
{
ProviderName = nameof(SerilogInput),
Timestamp = logEvent.Timestamp,
Level = ToLogLevel[logEvent.Level],
Keywords = 0
};
var payload = eventData.Payload;
// Prefer the built-in `Message` and `Exception` properties by adding them to the payload
// first. If other attached data items have conflicting names, they will be added as
// `Message_1` and so-on.
if (logEvent.Exception != null)
{
if (logEvent.Level >= LogEventLevel.Error)
{
EventMetadata eventMetadata = new EventMetadata(ExceptionData.ExceptionMetadataKind);
eventMetadata.Properties.Add(ExceptionData.ExceptionPropertyMoniker, "Exception");
eventData.SetMetadata(eventMetadata);
}
eventData.AddPayloadProperty("Exception", logEvent.Exception, healthReporter, nameof(SerilogInput));
}
// Inability to render the message, or any other LogEvent property, should not stop us from sending the event down the pipeline
try
{
eventData.AddPayloadProperty("Message", logEvent.RenderMessage(), healthReporter, nameof(SerilogInput));
}
catch (Exception e)
{
healthReporter.ReportWarning($"{nameof(SerilogInput)}: event message could not be rendered{Environment.NewLine}{e.ToString()}");
}
// MessageTemplate is always present on Serilog events
eventData.AddPayloadProperty("MessageTemplate", logEvent.MessageTemplate.Text, healthReporter, nameof(SerilogInput));
foreach (var property in logEvent.Properties.Where(property => property.Value != null))
{
try
{
eventData.AddPayloadProperty(property.Key, ToRawValue(property.Value), healthReporter, nameof(SerilogInput));
}
catch (Exception e)
{
healthReporter.ReportWarning($"{nameof(SerilogInput)}: event property '{property.Key}' could not be rendered{Environment.NewLine}{e.ToString()}");
}
}
return eventData;
}
private object ToRawValue(LogEventPropertyValue logEventValue)
{
// Special-case a few types of LogEventPropertyValue that allow us to maintain better type fidelity.
// For everything else take the default string rendering as the data.
ScalarValue scalarValue = logEventValue as ScalarValue;
if (scalarValue != null)
{
return scalarValue.Value;
}
SequenceValue sequenceValue = logEventValue as SequenceValue;
if (sequenceValue != null)
{
object[] arrayResult = sequenceValue.Elements.Select(e => valueSerializer(e)).ToArray();
return arrayResult;
}
StructureValue structureValue = logEventValue as StructureValue;
if (structureValue != null)
{
IDictionary<string, object> structureResult = new Dictionary<string, object>(structureValue.Properties.Count);
foreach (var property in structureValue.Properties)
{
structureResult[property.Name] = valueSerializer(property.Value);
}
if (structureValue.TypeTag != null)
{
structureResult["$type"] = structureValue.TypeTag;
}
return structureResult;
}
DictionaryValue dictionaryValue = logEventValue as DictionaryValue;
if (dictionaryValue != null)
{
IDictionary<string, object> dictionaryResult = dictionaryValue.Elements
.Where(kvPair => kvPair.Key.Value is string)
.ToDictionary(kvPair => (string)kvPair.Key.Value, kvPair => valueSerializer(kvPair.Value));
return dictionaryResult;
}
// Fall back to string rendering of the value
return logEventValue.ToString();
}
private object ToRawScalar(LogEventPropertyValue value)
{
ScalarValue scalarValue = value as ScalarValue;
if (scalarValue != null)
{
return scalarValue.Value;
}
return value.ToString();
}
}
}