forked from anaselhajjaji/log4net.Appender.Loki
-
Notifications
You must be signed in to change notification settings - Fork 2
/
LokiAppender.cs
91 lines (82 loc) · 3.39 KB
/
LokiAppender.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
using log4net.Appender;
using log4net.Core;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Text;
namespace Log4Net.Appender.Loki
{
public class LokiAppender : BufferingAppenderSkeleton
{
public string Application { get; set; }
public string Environment { get; set; }
public string ServiceUrl { get; set; }
public string BasicAuthUserName { get; set; }
public string BasicAuthPassword { get; set; }
public bool GZipCompression { get; set; }
public bool TrustSelfSignedCerts { get; set; }
private void PostLoggingEvent(LoggingEvent[] loggingEvents)
{
var labels = new LokiLabel[] {
new LokiLabel("Application", Application),
new LokiLabel("Environment", Environment)
};
var properties = new LokiProperty[] {
new LokiProperty("MachineName", System.Environment.MachineName),
new LokiProperty("ProcessName", Process.GetCurrentProcess().ProcessName)
};
var formatter = new LokiBatchFormatter(labels, properties);
var httpClient = new LokiHttpClient(TrustSelfSignedCerts);
if (httpClient is LokiHttpClient c)
{
LokiCredentials credentials;
if (!string.IsNullOrEmpty(BasicAuthUserName) && !string.IsNullOrEmpty(BasicAuthPassword))
{
credentials = new BasicAuthCredentials(ServiceUrl, BasicAuthUserName, BasicAuthPassword);
}
else
{
credentials = new NoAuthCredentials(ServiceUrl);
}
c.SetAuthCredentials(credentials);
}
StringBuilder sb = new StringBuilder();
using (var sc = new StringWriter(sb))
{
formatter.Format(loggingEvents, sc);
sc.Flush();
var loggingEventsStr = sb.ToString();
if (GZipCompression)
{
var compressedContent = CompressRequestContent(loggingEventsStr);
httpClient.PostAsync(LokiRouteBuilder.BuildPostUri(ServiceUrl), compressedContent);
}
else
{
var content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(loggingEventsStr)));
//var contentStr = content.ReadAsStringAsync().Result; // TO VERIFY
httpClient.PostAsync(LokiRouteBuilder.BuildPostUri(ServiceUrl), content);
}
}
}
protected override void SendBuffer(LoggingEvent[] events)
{
PostLoggingEvent(events);
}
private static HttpContent CompressRequestContent(string content)
{
var compressedStream = new MemoryStream();
using (var contentStream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
using (var gzipStream = new GZipStream(compressedStream, CompressionMode.Compress))
{
contentStream.CopyTo(gzipStream);
}
}
var httpContent = new ByteArrayContent(compressedStream.ToArray());
httpContent.Headers.Add("Content-encoding", "gzip");
return httpContent;
}
}
}