-
Notifications
You must be signed in to change notification settings - Fork 17
/
NewRelicFormatter.cs
216 lines (183 loc) · 7.67 KB
/
NewRelicFormatter.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
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Json;
namespace NewRelic.LogEnrichers.Serilog
{
public class NewRelicFormatter : ITextFormatter
{
private const string LinkingMetadataKey = "newrelic.linkingmetadata";
private const char JsonOpen = '{';
private const char JsonClose = '}';
private const char JsonDelim = ',';
private const char JsonColon = ':';
private const char JsonAtSign = '@';
private static readonly ScalarValue JsonNull = new ScalarValue(null);
private static readonly Dictionary<LogEventLevel, string> _cacheLogLevelNames =
Enum.GetValues(typeof(LogEventLevel))
.Cast<LogEventLevel>()
.ToDictionary(x => x, x => x.ToString());
private readonly JsonValueFormatter _valueFormatter = new JsonValueFormatter();
private readonly Dictionary<string, string> _propertyMappings = new Dictionary<string, string>();
/// <summary>
/// This formatter already handles these items. Users should not
/// override their output values.
/// </summary>
private readonly NewRelicLoggingProperty[] _reservedProperties = new[]
{
NewRelicLoggingProperty.Timestamp,
NewRelicLoggingProperty.ErrorMessage,
NewRelicLoggingProperty.ErrorClass,
NewRelicLoggingProperty.ErrorStack,
NewRelicLoggingProperty.MessageText,
NewRelicLoggingProperty.MessageTemplate,
NewRelicLoggingProperty.LogLevel,
};
private string _userPropertyPrefix;
public NewRelicFormatter()
{
_userPropertyPrefix = LoggingExtensions.UserPropertyPrefix;
}
public NewRelicFormatter WithPropertyMapping(string propertyName, NewRelicLoggingProperty outputAsNewRelicProperty)
{
if (_reservedProperties.Contains(outputAsNewRelicProperty))
{
throw new InvalidOperationException($"The New Relic Serilog Extension does not allow mapping of property {outputAsNewRelicProperty}");
}
_propertyMappings[propertyName] = LoggingExtensions.GetOutputName(outputAsNewRelicProperty);
return this;
}
public NewRelicFormatter WithUserPropertyPrefix(string userPropertyPrefix)
{
_userPropertyPrefix = userPropertyPrefix;
return this;
}
public void Format(LogEvent logEvent, TextWriter output)
{
if (logEvent == null)
{
throw new ArgumentNullException(nameof(logEvent));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
output.Write(JsonOpen);
WriteIntrinsicProperties(logEvent, output);
WriteExceptionProperties(logEvent.Exception, output);
WriteUserProperties(logEvent, output);
output.Write(JsonClose);
output.WriteLine();
}
private void WriteIntrinsicProperties(LogEvent logEvent, TextWriter output)
{
WriteTimestamp(logEvent.Timestamp.DateTime.ToUnixTimeMilliseconds(), output); // do this first to make commas in JSON easier
WriteFormattedJsonData(NewRelicLoggingProperty.LogLevel.GetOutputName(), _cacheLogLevelNames[logEvent.Level], output);
WriteFormattedJsonData(NewRelicLoggingProperty.MessageTemplate.GetOutputName(), logEvent.MessageTemplate, output);
WriteFormattedJsonData(NewRelicLoggingProperty.MessageText.GetOutputName(), logEvent.MessageTemplate.Render(logEvent.Properties), output);
}
private void WriteExceptionProperties(Exception exception, TextWriter output)
{
if (exception == null)
{
return;
}
WriteFormattedJsonData(NewRelicLoggingProperty.ErrorClass.GetOutputName(), exception.GetType().FullName, output);
if (!string.IsNullOrWhiteSpace(exception.Message))
{
WriteFormattedJsonData(NewRelicLoggingProperty.ErrorMessage.GetOutputName(), exception.Message, output);
}
if (!string.IsNullOrWhiteSpace(exception.StackTrace))
{
WriteFormattedJsonData(NewRelicLoggingProperty.ErrorStack.GetOutputName(), exception.StackTrace, output);
}
}
private void WriteLinkingMetadataProperties(LogEventPropertyValue nrPropValues, TextWriter output)
{
var nrPropValuesDic = nrPropValues as DictionaryValue;
if (nrPropValuesDic == null)
{
return;
}
foreach (var nrPropValue in nrPropValuesDic.Elements)
{
var propName = nrPropValue.Key;
var propValue = nrPropValue.Value;
WriteFormattedJsonData(propName.Value.ToString(), propValue, output);
}
}
private void WriteUserProperties(LogEvent logEvent, TextWriter output)
{
foreach (var kvp in logEvent.Properties)
{
var key = kvp.Key;
if (string.IsNullOrWhiteSpace(key))
{
continue;
}
if (key == LinkingMetadataKey)
{
WriteLinkingMetadataProperties(kvp.Value, output);
continue;
}
// We don't expect to receive any NR properties that have @ in their keys.
if (key[0] == JsonAtSign && key.Length >= 2 && key[1] != JsonAtSign)
{
key = JsonAtSign + key;
}
// If a custom property mapping exists, use it.
if (_propertyMappings.TryGetValue(key, out var jsonPropName))
{
WriteFormattedJsonData(jsonPropName, kvp.Value.ToString(), output);
}
else
{
WriteFormattedJsonData(_userPropertyPrefix + key, kvp.Value, output);
}
}
}
private void WriteTimestamp(long unixTimestampValue, TextWriter output)
{
JsonValueFormatter.WriteQuotedJsonString(NewRelicLoggingProperty.Timestamp.GetOutputName(), output);
output.Write(JsonColon);
output.Write(unixTimestampValue);
}
/// <summary>
/// Writes out a single formatted and escaped JSON data entry.
/// </summary>
private void WriteFormattedJsonData(string key, LogEventPropertyValue value, TextWriter output)
{
if (string.IsNullOrEmpty(key))
{
return;
}
output.Write(JsonDelim);
JsonValueFormatter.WriteQuotedJsonString(key, output);
output.Write(JsonColon);
_valueFormatter.Format(value, output);
}
private void WriteFormattedJsonData(string key, object value, TextWriter output)
{
if (string.IsNullOrEmpty(key))
{
return;
}
output.Write(JsonDelim);
JsonValueFormatter.WriteQuotedJsonString(key, output);
output.Write(JsonColon);
if (value == null)
{
_valueFormatter.Format(JsonNull, output);
}
else
{
JsonValueFormatter.WriteQuotedJsonString(value.ToString(), output);
}
}
}
}