-
Notifications
You must be signed in to change notification settings - Fork 16
/
NewRelicLogPayload.cs
84 lines (71 loc) · 2.82 KB
/
NewRelicLogPayload.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
using Newtonsoft.Json;
using Serilog.Events;
using Serilog.Sinks.NewRelic.Logs.Sinks.NewRelicLogs;
using System;
using System.Collections.Generic;
namespace Serilog.Sinks.NewRelic.Logs
{
public class NewRelicLogPayload
{
public NewRelicLogPayload() {}
public NewRelicLogPayload(string applicationName)
{
this.Common.Attributes.Add("application", applicationName);
}
[JsonProperty("common")]
public NewRelicLogCommon Common { get; set; } = new NewRelicLogCommon();
[JsonProperty("logs")]
public IList<NewRelicLogItem> Logs { get; set; } = new List<NewRelicLogItem>();
}
public class NewRelicLogCommon
{
[JsonProperty("attributes")]
public IDictionary<string, object> Attributes { get; set; } = new Dictionary<string, object>();
}
public class NewRelicLogItem
{
private const string NewRelicLinkingMetadata = "newrelic.linkingmetadata";
public NewRelicLogItem() {}
public NewRelicLogItem(LogEvent logEvent, IFormatProvider formatProvider)
{
this.Timestamp = logEvent.Timestamp.UtcDateTime.ToUnixTimestamp();
this.Message = logEvent.RenderMessage(formatProvider);
this.Attributes.Add("level", logEvent.Level.ToString());
this.Attributes.Add("stack_trace", logEvent.Exception?.StackTrace ?? "");
if (logEvent.Exception != null)
{
this.Attributes.Add("exception", logEvent.Exception.ToString() ?? "");
}
foreach (var property in logEvent.Properties)
{
this.AddProperty(property.Key, property.Value);
}
}
[JsonProperty("timestamp")]
public long Timestamp { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("attributes")]
public IDictionary<string, object> Attributes { get; set; } = new Dictionary<string, object>();
private void AddProperty(string key, LogEventPropertyValue value)
{
if (key.Equals(NewRelicLinkingMetadata, StringComparison.InvariantCultureIgnoreCase))
{
// unroll new relic distributed trace attributes
if (value is DictionaryValue newRelicProperties)
{
foreach (var property in newRelicProperties.Elements)
{
this.Attributes.Add(
NewRelicPropertyFormatter.Simplify(property.Key).ToString(),
NewRelicPropertyFormatter.Simplify(property.Value));
}
}
}
else
{
this.Attributes.Add(key, NewRelicPropertyFormatter.Simplify(value));
}
}
}
}