-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogFlake.cs
186 lines (151 loc) · 6.04 KB
/
LogFlake.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
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Options;
using NLogFlake.Constants;
using NLogFlake.Models;
using NLogFlake.Models.Options;
using Snappier;
namespace NLogFlake;
internal class LogFlake : ILogFlake, IDisposable
{
private Uri Server { get; set; }
private string? _hostname = Environment.MachineName;
private string AppId { get; set; }
private readonly ConcurrentQueue<PendingLog> _logsQueue = new();
private readonly ManualResetEvent _processLogs = new(false);
private readonly IHttpClientFactory _httpClientFactory;
private Thread LogsProcessorThread { get; set; }
private bool IsShuttingDown { get; set; }
internal int FailedPostRetries { get; set; } = 3;
internal bool EnableCompression { get; set; } = true;
internal void SetHostname() => SetHostname(null);
internal string? GetHostname() => _hostname;
internal void SetHostname(string? hostname) => _hostname = string.IsNullOrWhiteSpace(hostname) ? null : hostname;
public LogFlake(IOptions<LogFlakeOptions> logFlakeOptions, IHttpClientFactory httpClientFactory)
{
AppId = logFlakeOptions.Value.AppId!;
Server = new Uri(logFlakeOptions.Value.Endpoint ?? ServersConstants.PRODUCTION);
LogsProcessorThread = new Thread(LogsProcessor);
LogsProcessorThread.Start();
_httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
}
public void Dispose() => Shutdown();
~LogFlake() => Shutdown();
protected void Shutdown()
{
IsShuttingDown = true;
_processLogs.Set();
LogsProcessorThread.Join();
}
private void LogsProcessor()
{
SendLog(LogLevels.DEBUG, $"LogFlake started on {_hostname}");
_processLogs.WaitOne();
while (!_logsQueue.IsEmpty)
{
_ = _logsQueue.TryDequeue(out PendingLog? log);
log.Retries++;
bool success = Post(log.QueueName!, log.JsonString!).GetAwaiter().GetResult();
if (!success && log.Retries < FailedPostRetries)
{
_logsQueue.Enqueue(log);
}
_processLogs.Reset();
if (_logsQueue.IsEmpty && !IsShuttingDown)
{
_processLogs.WaitOne();
}
}
}
private async Task<bool> Post(string queueName, string jsonString)
{
if (queueName != QueuesConstants.LOGS && queueName != QueuesConstants.PERFORMANCES)
{
return false;
}
try
{
string requestUri = $"/api/ingestion/{AppId}/{queueName}";
HttpResponseMessage result = new(System.Net.HttpStatusCode.InternalServerError);
using HttpClient httpClient = _httpClientFactory.CreateClient(HttpClientConstants.ClientName);
httpClient.BaseAddress = Server;
if (EnableCompression)
{
byte[] jsonStringBytes = Encoding.UTF8.GetBytes(jsonString);
string base64String = Convert.ToBase64String(jsonStringBytes);
byte[] compressed = Snappy.CompressToArray(Encoding.UTF8.GetBytes(base64String));
ByteArrayContent content = new(compressed);
content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/octet-stream");
result = await httpClient.PostAsync(requestUri, content);
}
else
{
StringContent content = new(jsonString, Encoding.UTF8, "application/json");
result = await httpClient.PostAsync(requestUri, content);
}
return result.IsSuccessStatusCode;
}
catch (Exception)
{
return false;
}
}
public void SendLog(string content, Dictionary<string, object>? parameters = null) => SendLog(LogLevels.DEBUG, content, parameters);
public void SendLog(LogLevels level, string content, Dictionary<string, object>? parameters = null) => SendLog(level, null, content, parameters);
public void SendLog(LogLevels level, string? correlation, string? content, Dictionary<string, object>? parameters = null)
{
_logsQueue.Enqueue(new PendingLog
{
QueueName = QueuesConstants.LOGS,
JsonString = new LogObject
{
Level = level,
Hostname = GetHostname(),
Content = content!,
Correlation = correlation,
Parameters = parameters,
}.ToString()
});
_processLogs.Set();
}
public void SendException(Exception e) => SendException(e, null);
public void SendException(Exception e, string? correlation)
{
StringBuilder additionalTrace = new();
if (e.Data.Count > 0)
{
additionalTrace.Append($"{Environment.NewLine}Data:");
additionalTrace.Append($"{Environment.NewLine}{JsonSerializer.Serialize(e.Data, new JsonSerializerOptions { WriteIndented = true })}");
}
_logsQueue.Enqueue(new PendingLog
{
QueueName = QueuesConstants.LOGS,
JsonString = new LogObject
{
Level = LogLevels.EXCEPTION,
Hostname = GetHostname(),
Content = $"{e.Demystify()}{additionalTrace}",
Correlation = correlation,
}.ToString()
});
_processLogs.Set();
}
public void SendPerformance(string label, long duration)
{
_logsQueue.Enqueue(new PendingLog
{
QueueName = QueuesConstants.PERFORMANCES,
JsonString = new LogObject
{
Label = label,
Duration = duration,
}.ToString()
});
_processLogs.Set();
}
public IPerformanceCounter MeasurePerformance() => new PerformanceCounter(this);
public IPerformanceCounter MeasurePerformance(string label) => new PerformanceCounter(this, label);
}