|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using Microsoft.Extensions.Logging; |
| 5 | +using Newtonsoft.Json; |
| 6 | + |
| 7 | +namespace KubeOps.Operator.Logging |
| 8 | +{ |
| 9 | + internal class StructuredConsoleLogger : ILogger |
| 10 | + { |
| 11 | + private const string OriginalFormat = "{OriginalFormat}"; |
| 12 | + private readonly string _category; |
| 13 | + private readonly JsonSerializerSettings _jsonSettings; |
| 14 | + |
| 15 | + public StructuredConsoleLogger(string category, JsonSerializerSettings jsonSettings) |
| 16 | + { |
| 17 | + _category = category; |
| 18 | + _jsonSettings = jsonSettings; |
| 19 | + } |
| 20 | + |
| 21 | + public IDisposable BeginScope<TState>(TState state) => new LoggingNullScope(); |
| 22 | + |
| 23 | + public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; |
| 24 | + |
| 25 | + public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) |
| 26 | + { |
| 27 | + var message = new LogMessage |
| 28 | + { |
| 29 | + Category = _category, |
| 30 | + Message = formatter(state, exception), |
| 31 | + Timestamp = DateTime.UtcNow, |
| 32 | + }; |
| 33 | + |
| 34 | + if (state is IReadOnlyList<KeyValuePair<string, object>> parameters) |
| 35 | + { |
| 36 | + message.Parameters = new Dictionary<string, object>(); |
| 37 | + foreach (var (key, value) in parameters.Where(pair => pair.Key != OriginalFormat)) |
| 38 | + { |
| 39 | + message.Parameters.Add(key, value); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + if (exception != null) |
| 44 | + { |
| 45 | + message.ExceptionMessage = exception.Message; |
| 46 | + } |
| 47 | + |
| 48 | + Console.WriteLine(JsonConvert.SerializeObject(message, _jsonSettings)); |
| 49 | + } |
| 50 | + |
| 51 | + private struct LogMessage |
| 52 | + { |
| 53 | + public string Category { get; set; } |
| 54 | + |
| 55 | + public DateTime Timestamp { get; set; } |
| 56 | + |
| 57 | + public string Message { get; set; } |
| 58 | + |
| 59 | + public string ExceptionMessage { get; set; } |
| 60 | + |
| 61 | + public IDictionary<string, object> Parameters { get; set; } |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments