|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | + |
| 5 | +namespace SecureFolderFS.Shared.Logging |
| 6 | +{ |
| 7 | + internal sealed class FileOutputLogger : ILogger |
| 8 | + { |
| 9 | + private readonly string _categoryName; |
| 10 | + private readonly LogLevel _minLevel; |
| 11 | + private readonly FileOutputLoggerProvider _provider; |
| 12 | + |
| 13 | + public FileOutputLogger(string categoryName, LogLevel minLevel, FileOutputLoggerProvider provider) |
| 14 | + { |
| 15 | + _categoryName = categoryName; |
| 16 | + _minLevel = minLevel; |
| 17 | + _provider = provider; |
| 18 | + } |
| 19 | + |
| 20 | + /// <inheritdoc/> |
| 21 | + public bool IsEnabled(LogLevel logLevel) |
| 22 | + { |
| 23 | + return logLevel >= _minLevel && logLevel != LogLevel.None; |
| 24 | + } |
| 25 | + |
| 26 | + /// <inheritdoc/> |
| 27 | + public IDisposable? BeginScope<TState>(TState state) where TState : notnull |
| 28 | + { |
| 29 | + return null; |
| 30 | + } |
| 31 | + |
| 32 | + /// <inheritdoc/> |
| 33 | + public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) |
| 34 | + { |
| 35 | + if (!IsEnabled(logLevel)) |
| 36 | + return; |
| 37 | + |
| 38 | + var message = formatter(state, exception); |
| 39 | + var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); |
| 40 | + var level = GetLevelTag(logLevel); |
| 41 | + |
| 42 | + var line = $"[{timestamp}] {level} {_categoryName}: {message}"; |
| 43 | + if (exception is not null) |
| 44 | + line += $"{Environment.NewLine} >>> {exception}"; |
| 45 | + |
| 46 | + _provider.WriteMessage(line); |
| 47 | + } |
| 48 | + |
| 49 | + private static string GetLevelTag(LogLevel logLevel) => logLevel switch |
| 50 | + { |
| 51 | + LogLevel.Trace => "[TRC]", |
| 52 | + LogLevel.Debug => "[DBG]", |
| 53 | + LogLevel.Information => "[INF]", |
| 54 | + LogLevel.Warning => "[WRN]", |
| 55 | + LogLevel.Error => "[ERR]", |
| 56 | + LogLevel.Critical => "[CRT]", |
| 57 | + _ => "[???]" |
| 58 | + }; |
| 59 | + } |
| 60 | +} |
0 commit comments