/
JsonFormatter.cs
462 lines (404 loc) · 17 KB
/
JsonFormatter.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// Copyright 2013-2015 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Serilog.Formatting.Json;
/// <summary>
/// Formats log events in a simple JSON structure. Instances of this class
/// are safe for concurrent access by multiple threads.
/// </summary>
public class JsonFormatter : ITextFormatter
{
const string ExtensionPointObsoletionMessage = "Extension of JsonFormatter by subclassing is obsolete and will " +
"be removed in a future Serilog version. Write a custom formatter " +
"based on JsonValueFormatter instead. See https://github.com/serilog/serilog/pull/819.";
// Ignore obsoletion errors
#pragma warning disable 618
readonly bool _omitEnclosingObject;
readonly string _closingDelimiter;
readonly bool _renderMessage;
readonly IFormatProvider? _formatProvider;
readonly IDictionary<Type, Action<object, bool, TextWriter>> _literalWriters;
/// <summary>
/// Construct a <see cref="JsonFormatter"/>.
/// </summary>
/// <param name="closingDelimiter">A string that will be written after each log event is formatted.
/// If null, <see cref="Environment.NewLine"/> will be used.</param>
/// <param name="renderMessage">If true, the message will be rendered and written to the output as a
/// property named RenderedMessage.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
public JsonFormatter(
string? closingDelimiter = null,
bool renderMessage = false,
IFormatProvider? formatProvider = null)
: this(false, closingDelimiter, renderMessage, formatProvider)
{
}
/// <summary>
/// Construct a <see cref="JsonFormatter"/>.
/// </summary>
/// <param name="omitEnclosingObject">If true, the properties of the event will be written to
/// the output without enclosing braces. Otherwise, if false, each event will be written as a well-formed
/// JSON object.</param>
/// <param name="closingDelimiter">A string that will be written after each log event is formatted.
/// If null, <see cref="Environment.NewLine"/> will be used. Ignored if <paramref name="omitEnclosingObject"/>
/// is true.</param>
/// <param name="renderMessage">If true, the message will be rendered and written to the output as a
/// property named RenderedMessage.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
[Obsolete("The omitEnclosingObject parameter is obsolete and will be removed in a future Serilog version.")]
public JsonFormatter(
bool omitEnclosingObject,
string? closingDelimiter = null,
bool renderMessage = false,
IFormatProvider? formatProvider = null)
{
_omitEnclosingObject = omitEnclosingObject;
_closingDelimiter = closingDelimiter ?? Environment.NewLine;
_renderMessage = renderMessage;
_formatProvider = formatProvider;
_literalWriters = new Dictionary<Type, Action<object, bool, TextWriter>>
{
{ typeof(bool), (v, _, w) => WriteBoolean((bool)v, w) },
{ typeof(char), (v, _, w) => WriteString(((char)v).ToString(), w) },
{ typeof(byte), WriteToString },
{ typeof(sbyte), WriteToString },
{ typeof(short), WriteToString },
{ typeof(ushort), WriteToString },
{ typeof(int), WriteToString },
{ typeof(uint), WriteToString },
{ typeof(long), WriteToString },
{ typeof(ulong), WriteToString },
{ typeof(float), (v, _, w) => WriteSingle((float)v, w) },
{ typeof(double), (v, _, w) => WriteDouble((double)v, w) },
{ typeof(decimal), WriteToString },
{ typeof(string), (v, _, w) => WriteString((string)v, w) },
{ typeof(DateTime), (v, _, w) => WriteDateTime((DateTime)v, w) },
{ typeof(DateTimeOffset), (v, _, w) => WriteOffset((DateTimeOffset)v, w) },
#if FEATURE_DATE_AND_TIME_ONLY
{ typeof(DateOnly), (v, _, w) => WriteDateOnly((DateOnly)v, w) },
{ typeof(TimeOnly), (v, _, w) => WriteTimeOnly((TimeOnly)v, w) },
#endif
{ typeof(ScalarValue), (v, q, w) => WriteLiteral(((ScalarValue)v).Value, w, q) },
{ typeof(SequenceValue), (v, _, w) => WriteSequence(((SequenceValue)v).Elements, w) },
{ typeof(DictionaryValue), (v, _, w) => WriteDictionary(((DictionaryValue)v).Elements, w) },
{ typeof(StructureValue), (v, _, w) => WriteStructure(((StructureValue)v).TypeTag, ((StructureValue)v).Properties, w) },
};
}
/// <summary>
/// Format the log event into the output.
/// </summary>
/// <param name="logEvent">The event to format.</param>
/// <param name="output">The output.</param>
/// <exception cref="ArgumentNullException">When <paramref name="logEvent"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="output"/> is <code>null</code></exception>
public void Format(LogEvent logEvent, TextWriter output)
{
Guard.AgainstNull(logEvent);
Guard.AgainstNull(output);
if (!_omitEnclosingObject)
output.Write("{");
var delim = "";
WriteTimestamp(logEvent.Timestamp, ref delim, output);
WriteLevel(logEvent.Level, ref delim, output);
WriteMessageTemplate(logEvent.MessageTemplate.Text, ref delim, output);
if (_renderMessage)
{
var message = logEvent.RenderMessage(_formatProvider);
WriteRenderedMessage(message, ref delim, output);
}
if (logEvent.Exception != null)
WriteException(logEvent.Exception, ref delim, output);
if (logEvent.Properties.Count != 0)
WriteProperties(logEvent.Properties, output);
var tokensWithFormat = logEvent.MessageTemplate.Tokens
.OfType<PropertyToken>()
.Where(pt => pt.Format != null)
.GroupBy(pt => pt.PropertyName)
.ToArray();
if (tokensWithFormat.Length != 0)
{
WriteRenderings(tokensWithFormat, logEvent.Properties, output);
}
if (!_omitEnclosingObject)
{
output.Write("}");
output.Write(_closingDelimiter);
}
}
/// <summary>
/// Adds a writer function for a given type.
/// </summary>
/// <param name="type">The type of values, which <paramref name="writer" /> handles.</param>
/// <param name="writer">The function, which writes the values.</param>
/// <exception cref="ArgumentNullException">When <paramref name="type"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="writer"/> is <code>null</code></exception>
[Obsolete(ExtensionPointObsoletionMessage)]
protected void AddLiteralWriter(Type type, Action<object, TextWriter> writer)
{
Guard.AgainstNull(type);
Guard.AgainstNull(writer);
_literalWriters[type] = (v, _, w) => writer(v, w);
}
/// <summary>
/// Writes out individual renderings of attached properties
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteRenderings(IGrouping<string, PropertyToken>[] tokensWithFormat, IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
output.Write(",\"{0}\":{{", "Renderings");
WriteRenderingsValues(tokensWithFormat, properties, output);
output.Write("}");
}
/// <summary>
/// Writes out the values of individual renderings of attached properties
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteRenderingsValues(IGrouping<string, PropertyToken>[] tokensWithFormat, IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
var propertyDelimiter = "";
foreach (var propertyFormats in tokensWithFormat)
{
output.Write(propertyDelimiter);
propertyDelimiter = ",";
output.Write("\"");
output.Write(propertyFormats.Key);
output.Write("\":[");
var formatDelimiter = "";
foreach (var format in propertyFormats)
{
output.Write(formatDelimiter);
formatDelimiter = ",";
output.Write("{");
var elementDelimiter = "";
WriteJsonProperty("Format", format.Format, ref elementDelimiter, output);
var sw = new StringWriter();
MessageTemplateRenderer.RenderPropertyToken(format, properties, sw, _formatProvider, isLiteral: true, isJson: false);
WriteJsonProperty("Rendering", sw.ToString(), ref elementDelimiter, output);
output.Write("}");
}
output.Write("]");
}
}
/// <summary>
/// Writes out the attached properties
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteProperties(IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
output.Write(",\"{0}\":{{", "Properties");
WritePropertiesValues(properties, output);
output.Write("}");
}
/// <summary>
/// Writes out the attached properties values
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WritePropertiesValues(IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
var precedingDelimiter = "";
foreach (var property in properties)
{
WriteJsonProperty(property.Key, property.Value, ref precedingDelimiter, output);
}
}
/// <summary>
/// Writes out the attached exception
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteException(Exception exception, ref string delim, TextWriter output)
{
WriteJsonProperty("Exception", exception, ref delim, output);
}
/// <summary>
/// (Optionally) writes out the rendered message
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteRenderedMessage(string message, ref string delim, TextWriter output)
{
WriteJsonProperty("RenderedMessage", message, ref delim, output);
}
/// <summary>
/// Writes out the message template for the logevent.
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteMessageTemplate(string template, ref string delim, TextWriter output)
{
WriteJsonProperty("MessageTemplate", template, ref delim, output);
}
/// <summary>
/// Writes out the log level
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteLevel(LogEventLevel level, ref string delim, TextWriter output)
{
WriteJsonProperty("Level", level, ref delim, output);
}
/// <summary>
/// Writes out the log timestamp
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteTimestamp(DateTimeOffset timestamp, ref string delim, TextWriter output)
{
WriteJsonProperty("Timestamp", timestamp, ref delim, output);
}
/// <summary>
/// Writes out a structure property
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteStructure(string? typeTag, IEnumerable<LogEventProperty> properties, TextWriter output)
{
output.Write("{");
var delim = "";
if (typeTag != null)
WriteJsonProperty("_typeTag", typeTag, ref delim, output);
foreach (var property in properties)
WriteJsonProperty(property.Name, property.Value, ref delim, output);
output.Write("}");
}
/// <summary>
/// Writes out a sequence property
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteSequence(IEnumerable elements, TextWriter output)
{
output.Write("[");
var delim = "";
foreach (var value in elements)
{
output.Write(delim);
delim = ",";
WriteLiteral(value, output);
}
output.Write("]");
}
/// <summary>
/// Writes out a dictionary
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteDictionary(IReadOnlyDictionary<ScalarValue, LogEventPropertyValue> elements, TextWriter output)
{
output.Write("{");
var delim = "";
foreach (var element in elements)
{
output.Write(delim);
delim = ",";
WriteLiteral(element.Key, output, forceQuotation: true);
output.Write(":");
WriteLiteral(element.Value, output);
}
output.Write("}");
}
/// <summary>
/// Writes out a json property with the specified value on output writer
/// </summary>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteJsonProperty(string name, object? value, ref string precedingDelimiter, TextWriter output)
{
output.Write(precedingDelimiter);
output.Write("\"");
output.Write(name);
output.Write("\":");
WriteLiteral(value, output);
precedingDelimiter = ",";
}
/// <summary>
/// Allows a subclass to write out objects that have no configured literal writer.
/// </summary>
/// <param name="value">The value to be written as a json construct</param>
/// <param name="output">The writer to write on</param>
[Obsolete(ExtensionPointObsoletionMessage)]
protected virtual void WriteLiteralValue(object value, TextWriter output)
{
WriteString(value.ToString() ?? "", output);
}
void WriteLiteral(object? value, TextWriter output, bool forceQuotation = false)
{
if (value == null)
{
output.Write("null");
return;
}
if (_literalWriters.TryGetValue(value.GetType(), out var writer))
{
writer(value, forceQuotation, output);
return;
}
WriteLiteralValue(value, output);
}
static void WriteToString(object number, bool quote, TextWriter output)
{
if (quote) output.Write('"');
if (number is IFormattable fmt)
output.Write(fmt.ToString(null, CultureInfo.InvariantCulture));
else
output.Write(number.ToString());
if (quote) output.Write('"');
}
static void WriteBoolean(bool value, TextWriter output)
{
output.Write(value ? "true" : "false");
}
static void WriteSingle(float value, TextWriter output)
{
output.Write(value.ToString("R", CultureInfo.InvariantCulture));
}
static void WriteDouble(double value, TextWriter output)
{
output.Write(value.ToString("R", CultureInfo.InvariantCulture));
}
static void WriteOffset(DateTimeOffset value, TextWriter output)
{
output.Write("\"");
output.Write(value.ToString("o"));
output.Write("\"");
}
static void WriteDateTime(DateTime value, TextWriter output)
{
output.Write("\"");
output.Write(value.ToString("o"));
output.Write("\"");
}
#if FEATURE_DATE_AND_TIME_ONLY
static void WriteDateOnly(DateOnly value, TextWriter output)
{
output.Write("\"");
output.Write(value.ToString("yyyy-MM-dd"));
output.Write("\"");
}
static void WriteTimeOnly(TimeOnly value, TextWriter output)
{
output.Write("\"");
output.Write(value.ToString("O"));
output.Write("\"");
}
#endif
static void WriteString(string value, TextWriter output)
{
JsonValueFormatter.WriteQuotedJsonString(value, output);
}
/// <summary>
/// Perform simple JSON string escaping on <paramref name="s"/>.
/// </summary>
/// <param name="s">A raw string.</param>
/// <returns>A JSON-escaped version of <paramref name="s"/>.</returns>
[Obsolete("Use JsonValueFormatter.WriteQuotedJsonString() instead."), EditorBrowsable(EditorBrowsableState.Never)]
public static string? Escape(string? s)
{
if (s == null) return null;
var escapedResult = new StringWriter();
JsonValueFormatter.WriteQuotedJsonString(s, escapedResult);
var quoted = escapedResult.ToString();
return quoted.Substring(1, quoted.Length - 2);
}
}