forked from travelrepublic/NLog.Targets.Gelf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNLog.Targets.Gelf.cs
251 lines (201 loc) · 8.74 KB
/
NLog.Targets.Gelf.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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Newtonsoft.Json;
using NLog.Config;
namespace NLog.Targets.Gelf
{
[Target("Gelf")]
public sealed class GelfTarget : Target
{
#region Private Members
private static readonly string HostName = Dns.GetHostName();
private static readonly Socket SocketClient = new Socket(SocketType.Dgram, ProtocolType.Udp);
private static readonly ConcurrentDictionary<string, IPEndPoint> EndPoints = new ConcurrentDictionary<string, IPEndPoint>();
private const int ShortMessageLength = 250;
private const int MaxMessageIdSize = 8;
private const int MaxNumberOfChunksAllowed = 128;
#endregion
#region Public properties
[RequiredParameter]
public string GelfServer { get; set; }
public int Port { get; set; }
public string Facility { get; set; }
public int MaxChunkSize { get; set; }
#endregion
#region Public Constructors
public GelfTarget()
{
GelfServer = "127.0.0.1";
Port = 12201;
Facility = null;
MaxChunkSize = 1024;
}
#endregion
#region Overridden NLog methods
/// <summary>
/// This is where we hook into NLog, by overriding the Write method.
/// </summary>
/// <param name="logEvent">The NLog.LogEventInfo </param>
protected override void Write(LogEventInfo logEvent)
{
try
{
SendMessage(GelfServer, Port, CreateGelfJsonFromLoggingEvent(logEvent));
}
catch (Exception exception)
{
// If there's an error then log the message.
SendMessage(GelfServer, Port, CreateFatalGelfJson(exception));
}
}
#endregion
#region Private Methods
private void SendMessage(string gelfServer, int serverPort, string message)
{
var endPoint = GetIPEndPoint(gelfServer, serverPort);
var gzipMessage = GzipMessage(message);
if (gzipMessage.Length > MaxChunkSize)
{
var chunkCount = (gzipMessage.Length / MaxChunkSize) + 1;
if (chunkCount > MaxNumberOfChunksAllowed)
return;
var messageId = GenerateMessageId();
for (var i = 0; i < chunkCount; i++)
{
var messageChunkPrefix = CreateChunkedMessagePart(messageId, i, chunkCount);
var skip = i * MaxChunkSize;
var messageChunkSuffix = gzipMessage.Skip(skip).Take(MaxChunkSize).ToArray();
var messageChunkFull = new byte[messageChunkPrefix.Length + messageChunkSuffix.Length];
messageChunkPrefix.CopyTo(messageChunkFull, 0);
messageChunkSuffix.CopyTo(messageChunkFull, messageChunkPrefix.Length);
SocketClient.SendTo(messageChunkFull, 0, messageChunkFull.Length, SocketFlags.None, endPoint);
}
}
else
{
SocketClient.SendTo(gzipMessage, 0, gzipMessage.Length, SocketFlags.None, endPoint);
}
}
private static IPEndPoint GetIPEndPoint(string gelfServer, int serverPort)
{
return EndPoints.GetOrAdd(gelfServer,
s =>
{
var hostAddress = Dns.GetHostAddresses(gelfServer).FirstOrDefault();
return hostAddress == null ? null : new IPEndPoint(hostAddress, serverPort);
});
}
private static byte[] GzipMessage(string message)
{
var buffer = Encoding.UTF8.GetBytes(message);
var stream = new MemoryStream();
using (var gZipStream = new GZipStream(stream, CompressionMode.Compress, true))
{
gZipStream.Write(buffer, 0, buffer.Length);
}
stream.Position = 0;
var compressed = new byte[stream.Length];
stream.Read(compressed, 0, compressed.Length);
return compressed;
}
private string CreateGelfJsonFromLoggingEvent(LogEventInfo logEventInfo)
{
string shortMessage = null;
if (logEventInfo.FormattedMessage != null)
{
shortMessage = logEventInfo.FormattedMessage.Length > ShortMessageLength
? logEventInfo.FormattedMessage.Substring(0, ShortMessageLength - 1)
: logEventInfo.FormattedMessage;
}
var gelfMessage = new GelfMessage
{
Facility = Facility ?? "GELF",
FullMessage = logEventInfo.FormattedMessage,
Host = HostName,
Level = logEventInfo.Level.GelfSeverity(),
ShortMessage = shortMessage,
Logger = logEventInfo.LoggerName ?? ""
};
if (Activity.Current?.RootId != null)
gelfMessage.RequestId = Activity.Current?.RootId;
if (logEventInfo.Properties != null)
{
object notes;
if (logEventInfo.Properties.TryGetValue("Notes", out notes))
{
gelfMessage.Notes = (string) notes;
}
}
if (logEventInfo.Exception == null) return JsonConvert.SerializeObject(gelfMessage);
var exceptionToLog = logEventInfo.Exception;
while (exceptionToLog.InnerException != null)
{
exceptionToLog = exceptionToLog.InnerException;
}
gelfMessage.ExceptionType = exceptionToLog.GetType().Name;
gelfMessage.ExceptionMessage = exceptionToLog.Message;
gelfMessage.StackTrace = exceptionToLog.StackTrace;
return JsonConvert.SerializeObject(gelfMessage);
}
private string CreateFatalGelfJson(Exception exception)
{
var gelfMessage = new GelfMessage
{
Facility = Facility ?? "GELF",
FullMessage = "Error sending message in NLog.Targets.Gelf",
Host = HostName,
Level = LogLevel.Fatal.GelfSeverity(),
ShortMessage = "Error sending message in NLog.Targets.Gelf"
};
if (Activity.Current?.RootId != null)
gelfMessage.RequestId = Activity.Current?.RootId;
if (exception == null) return JsonConvert.SerializeObject(gelfMessage);
var exceptioToLog = exception;
while (exceptioToLog.InnerException != null)
{
exceptioToLog = exceptioToLog.InnerException;
}
gelfMessage.ExceptionType = exceptioToLog.GetType().Name;
gelfMessage.ExceptionMessage = exceptioToLog.Message;
gelfMessage.StackTrace = exceptioToLog.StackTrace;
return JsonConvert.SerializeObject(gelfMessage);
}
private static byte[] CreateChunkedMessagePart(string messageId, int chunkNumber, int chunkCount)
{
//Chunked GELF ID: 0x1e 0x0f (identifying this message as a chunked GELF message)
var result = new List<byte>
{
Convert.ToByte(30),
Convert.ToByte(15)
};
//Message ID: 32 bytes
result.AddRange(Encoding.Default.GetBytes(messageId));
result.AddRange(GetChunkPart(chunkNumber, chunkCount));
return result.ToArray<byte>();
}
private static IEnumerable<byte> GetChunkPart(int chunkNumber, int chunkCount)
{
return new List<byte>
{
Convert.ToByte(chunkNumber),
Convert.ToByte(chunkCount)
};
}
private static string GenerateMessageId()
{
var random = new Random((int) DateTime.Now.Ticks);
var r = random.Next(10000000).ToString("00000000");
//Message ID: 8 bytes
return r.Substring(0, MaxMessageIdSize);
}
#endregion
}
}