-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInMemoryLogger.cs
More file actions
79 lines (65 loc) · 2.28 KB
/
InMemoryLogger.cs
File metadata and controls
79 lines (65 loc) · 2.28 KB
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
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
namespace EntglDb.Test.Maui;
public class InMemoryLoggerProvider : ILoggerProvider
{
private readonly ConcurrentQueue<LogEntry> _logs;
public InMemoryLoggerProvider(ConcurrentQueue<LogEntry> logs)
{
_logs = logs;
}
public ILogger CreateLogger(string categoryName)
{
return new InMemoryLogger(categoryName, _logs);
}
public void Dispose()
{
}
}
public class InMemoryLogger : ILogger
{
private readonly string _categoryName;
private readonly ConcurrentQueue<LogEntry> _logs;
public InMemoryLogger(string categoryName, ConcurrentQueue<LogEntry> logs)
{
_categoryName = categoryName;
_logs = logs;
}
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
var message = formatter(state, exception);
var entry = new LogEntry
{
Timestamp = DateTime.Now,
Level = logLevel,
Category = _categoryName,
Message = message,
Exception = exception
};
_logs.Enqueue(entry);
// Keep size manageable
if (_logs.Count > 1000)
{
_logs.TryDequeue(out _);
}
}
}
public class LogEntry
{
public DateTime Timestamp { get; set; }
public LogLevel Level { get; set; }
public string Category { get; set; }
public string Message { get; set; }
public Exception? Exception { get; set; }
public string Formatted => $"[{Timestamp:HH:mm:ss}] [{Level}] {Category}: {Message} {(Exception != null ? Exception.ToString() : "")}";
public Color Color => Level switch
{
LogLevel.Error or LogLevel.Critical => Colors.Red,
LogLevel.Warning => Colors.Orange,
LogLevel.Information => Colors.Black, // Will adjust validation for Dark Mode via binding/style ideally, but sticking to basic for now.
_ => Colors.Gray
};
}