Code
·
346 lines
·
9861 bytes
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346using System.Text.Json;
using MongoDB.Bson;
using MongoDB.Driver;
using SeriLoog.Models;
namespace SeriLoog.Services;
public sealed class LogQuery
{
public int Page { get; set; } = 1;
public int PageSize { get; set; } = 25;
public string[]? Levels { get; set; }
public string? Search { get; set; }
public DateTimeOffset? From { get; set; }
public DateTimeOffset? To { get; set; }
public string Source { get; set; } = "mongo";
}
public sealed class LogQueryService(LogStoreOptions options, ILogger<LogQueryService> logger)
{
public async Task<LogQueryResult> QueryAsync(LogQuery query, CancellationToken ct)
{
if (string.Equals(query.Source, "file", StringComparison.OrdinalIgnoreCase))
{
return QueryFile(query);
}
try
{
return await QueryMongoAsync(query, ct);
}
catch (Exception ex)
{
logger.LogWarning(ex, "MongoDB unavailable, falling back to file log source");
var result = QueryFile(query);
result.Warning = $"MongoDB unavailable ({ex.Message}). Showing file log instead.";
return result;
}
}
private async Task<LogQueryResult> QueryMongoAsync(LogQuery query, CancellationToken ct)
{
var client = new MongoClient(options.MongoConnectionString);
var db = client.GetDatabase(options.MongoDatabase);
var collection = db.GetCollection<BsonDocument>(options.MongoCollection);
var filters = new List<FilterDefinition<BsonDocument>>();
var builder = Builders<BsonDocument>.Filter;
if (query.Levels is { Length: > 0 })
{
var levelFilters = query.Levels.Select(l =>
builder.Regex("Level", new BsonRegularExpression($"^{System.Text.RegularExpressions.Regex.Escape(l)}", "i")));
filters.Add(builder.Or(levelFilters));
}
if (!string.IsNullOrWhiteSpace(query.Search))
{
var pattern = new BsonRegularExpression(System.Text.RegularExpressions.Regex.Escape(query.Search), "i");
filters.Add(builder.Or(
builder.Regex("RenderedMessage", pattern),
builder.Regex("MessageTemplate", pattern),
builder.Regex("Exception", pattern)));
}
if (query.From is not null)
{
filters.Add(builder.Gte("Timestamp", query.From.Value.UtcDateTime));
}
if (query.To is not null)
{
filters.Add(builder.Lte("Timestamp", query.To.Value.UtcDateTime));
}
var filter = filters.Count > 0 ? builder.And(filters) : builder.Empty;
var total = await collection.CountDocumentsAsync(filter, cancellationToken: ct);
var page = Math.Max(1, query.Page);
var pageSize = Math.Clamp(query.PageSize, 1, 500);
var docs = await collection.Find(filter)
.SortByDescending(d => d["Timestamp"])
.Skip((page - 1) * pageSize)
.Limit(pageSize)
.ToListAsync(ct);
var items = docs.Select(MapMongoDocument).ToList();
return new LogQueryResult
{
Items = items,
Total = total,
Page = page,
PageSize = pageSize,
Source = "mongo"
};
}
private static LogEntryDto MapMongoDocument(BsonDocument doc)
{
string GetString(params string[] names)
{
foreach (var name in names)
{
if (doc.TryGetValue(name, out var v) && !v.IsBsonNull)
return v.IsString ? v.AsString : v.ToString() ?? "";
}
return "";
}
DateTimeOffset GetTimestamp()
{
foreach (var name in new[] { "Timestamp", "UtcTimeStamp", "@t" })
{
if (doc.TryGetValue(name, out var v) && !v.IsBsonNull)
{
return v.BsonType == BsonType.DateTime
? new DateTimeOffset(v.ToUniversalTime(), TimeSpan.Zero)
: DateTimeOffset.Parse(v.ToString()!);
}
}
return DateTimeOffset.UtcNow;
}
var properties = new Dictionary<string, object?>();
if (doc.TryGetValue("Properties", out var propsVal) && propsVal.IsBsonDocument)
{
foreach (var el in propsVal.AsBsonDocument)
{
properties[el.Name] = BsonTypeMapper.MapToDotNetValue(el.Value);
}
}
var id = doc.TryGetValue("_id", out var idVal) ? idVal.ToString() ?? "" : "";
var json = doc.ToJson(new MongoDB.Bson.IO.JsonWriterSettings { Indent = true });
return new LogEntryDto
{
Id = id ?? "",
Timestamp = GetTimestamp(),
Level = NormalizeLevel(GetString("Level")),
Message = GetString("RenderedMessage", "MessageTemplate"),
MessageTemplate = GetString("MessageTemplate"),
Exception = doc.TryGetValue("Exception", out var exVal) && !exVal.IsBsonNull ? exVal.ToString() : null,
Properties = properties,
Source = "mongo",
RawJson = json
};
}
private LogQueryResult QueryFile(LogQuery query)
{
if (string.IsNullOrWhiteSpace(options.LogFilePath))
{
return new LogQueryResult
{
Items = [],
Total = 0,
Page = Math.Max(1, query.Page),
PageSize = Math.Clamp(query.PageSize, 1, 500),
Source = "file",
Warning = "File logging is not configured (MongoDb:LogFilePath is empty)."
};
}
var dir = Path.GetDirectoryName(Path.GetFullPath(options.LogFilePath)) ?? ".";
var baseName = Path.GetFileNameWithoutExtension(options.LogFilePath).TrimEnd('-');
var ext = Path.GetExtension(options.LogFilePath);
var allLines = new List<string>();
if (Directory.Exists(dir))
{
var files = Directory.GetFiles(dir, $"{baseName}*{ext}").OrderByDescending(f => f);
foreach (var f in files)
{
try
{
using var stream = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var reader = new StreamReader(stream);
while (reader.ReadLine() is { } line)
{
if (!string.IsNullOrWhiteSpace(line)) allLines.Add(line);
}
}
catch (IOException)
{
// file locked/rolling, skip
}
}
}
var entries = allLines.Select(ParseCompactJsonLine).Where(e => e is not null).Select(e => e!).ToList();
entries.Reverse(); // newest first (file lines are chronological)
IEnumerable<LogEntryDto> filtered = entries;
if (query.Levels is { Length: > 0 })
{
var set = new HashSet<string>(query.Levels, StringComparer.OrdinalIgnoreCase);
filtered = filtered.Where(e => set.Contains(e.Level));
}
if (!string.IsNullOrWhiteSpace(query.Search))
{
var s = query.Search;
filtered = filtered.Where(e =>
e.Message.Contains(s, StringComparison.OrdinalIgnoreCase) ||
(e.Exception?.Contains(s, StringComparison.OrdinalIgnoreCase) ?? false));
}
if (query.From is not null)
{
var from = query.From.Value;
filtered = filtered.Where(e => e.Timestamp >= from);
}
if (query.To is not null)
{
var to = query.To.Value;
filtered = filtered.Where(e => e.Timestamp <= to);
}
var list = filtered.ToList();
var total = list.Count;
var page = Math.Max(1, query.Page);
var pageSize = Math.Clamp(query.PageSize, 1, 500);
var pageItems = list.Skip((page - 1) * pageSize).Take(pageSize).ToList();
return new LogQueryResult
{
Items = pageItems,
Total = total,
Page = page,
PageSize = pageSize,
Source = "file"
};
}
private static LogEntryDto? ParseCompactJsonLine(string line)
{
try
{
using var doc = JsonDocument.Parse(line);
var root = doc.RootElement;
var properties = new Dictionary<string, object?>();
string? messageTemplate = null;
string? exception = null;
var timestamp = DateTimeOffset.UtcNow;
var level = "Information";
foreach (var prop in root.EnumerateObject())
{
switch (prop.Name)
{
case "@t":
timestamp = DateTimeOffset.Parse(prop.Value.GetString()!, null, System.Globalization.DateTimeStyles.AssumeUniversal);
break;
case "@mt":
messageTemplate = prop.Value.GetString();
break;
case "@l":
level = prop.Value.GetString() ?? "Information";
break;
case "@x":
exception = prop.Value.GetString();
break;
case "@m":
case "@i":
case "@r":
break;
default:
properties[prop.Name] = JsonElementToObject(prop.Value);
break;
}
}
var message = RenderMessageTemplate(messageTemplate ?? "", properties);
return new LogEntryDto
{
Id = Guid.NewGuid().ToString("N"),
Timestamp = timestamp,
Level = NormalizeLevel(level),
Message = message,
MessageTemplate = messageTemplate,
Exception = exception,
Properties = properties,
Source = "file",
RawJson = System.Text.Json.JsonSerializer.Serialize(JsonDocument.Parse(line).RootElement, new JsonSerializerOptions { WriteIndented = true })
};
}
catch
{
return null;
}
}
private static readonly System.Text.RegularExpressions.Regex TokenRegex =
new(@"\{(@|\$)?(?<name>[a-zA-Z_][a-zA-Z0-9_]*)(?<format>:[^}]+)?\}", System.Text.RegularExpressions.RegexOptions.Compiled);
private static string RenderMessageTemplate(string template, Dictionary<string, object?> properties)
{
return TokenRegex.Replace(template, match =>
{
var name = match.Groups["name"].Value;
if (!properties.TryGetValue(name, out var value))
return match.Value;
var format = match.Groups["format"].Success ? match.Groups["format"].Value[1..] : null;
if (format is not null && value is IFormattable formattable)
{
try { return formattable.ToString(format, System.Globalization.CultureInfo.InvariantCulture); }
catch { /* fall through to plain rendering */ }
}
return value?.ToString() ?? "";
});
}
private static object? JsonElementToObject(JsonElement el) => el.ValueKind switch
{
JsonValueKind.String => el.GetString(),
JsonValueKind.Number => el.TryGetInt64(out var l) ? l : el.GetDouble(),
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Null => null,
_ => el.GetRawText()
};
private static string NormalizeLevel(string level) => level switch
{
"Verbose" or "VRB" or "Trace" => "Verbose",
"Debug" or "DBG" => "Debug",
"Information" or "INF" or "Info" => "Information",
"Warning" or "WRN" or "Warn" => "Warning",
"Error" or "ERR" => "Error",
"Fatal" or "FTL" or "Critical" => "Fatal",
"" => "Information",
_ => level
};
}