From 4754995036e2ceaed35d337101bc1309b27d6b6e Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Mon, 8 Jul 2024 22:11:23 +0800 Subject: [PATCH] feat: update DelegateLoggerProvider --- .../MicrosoftLoggingLoggerExtensions.cs | 52 +++++++++++++++---- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/src/WeihanLi.Common/Logging/MicrosoftLoggingLoggerExtensions.cs b/src/WeihanLi.Common/Logging/MicrosoftLoggingLoggerExtensions.cs index bb028454..87e8633c 100644 --- a/src/WeihanLi.Common/Logging/MicrosoftLoggingLoggerExtensions.cs +++ b/src/WeihanLi.Common/Logging/MicrosoftLoggingLoggerExtensions.cs @@ -1,6 +1,8 @@ using Microsoft.Extensions.DependencyInjection; using System.Collections.Concurrent; +using System.Diagnostics; using WeihanLi.Common; +using WeihanLi.Common.Helpers; using WeihanLi.Common.Logging; using WeihanLi.Common.Services; @@ -12,7 +14,45 @@ public sealed class DelegateLoggerProvider(Action { - Console.WriteLine(@$"[{level}][{category}] {msg}\n{exception}"); + var (foregroundColor, backgroundColor) = GetConsoleColorForLogLevel(level); + var levelText = GetLogLevelText(level); + var dateTime = DateTimeOffset.Now; + var message = @$"[{levelText}][{category}] {dateTime} {msg}"; + if (exception is not null) + { + message = $"{message}{Environment.NewLine}{exception}"; + } + + ConsoleHelper.WriteLineWithColor(message, foregroundColor, backgroundColor); + if (level is LogLevel.Trace) + { + Trace.WriteLine(message); + } + + return; + + static (ConsoleColor? ForegroundColor, ConsoleColor? BackgroundColor) GetConsoleColorForLogLevel(LogLevel logLevel) + => logLevel switch + { + LogLevel.Trace or LogLevel.Debug => (ConsoleColor.DarkGray, ConsoleColor.Black), + LogLevel.Information => (ConsoleColor.DarkGreen, ConsoleColor.Black), + LogLevel.Warning => (ConsoleColor.Yellow, ConsoleColor.Black), + LogLevel.Error => (ConsoleColor.Black, ConsoleColor.DarkRed), + LogLevel.Critical => (ConsoleColor.White, ConsoleColor.DarkRed), + _ => (null, null) + }; + + static string GetLogLevelText(LogLevel logLevel) + => logLevel switch + { + LogLevel.Trace => "trce", + LogLevel.Debug => "dbug", + LogLevel.Information => "info", + LogLevel.Warning => "warn", + LogLevel.Error => "fail", + LogLevel.Critical => "crit", + _ => logLevel.ToString().ToLowerInvariant() + }; }); private readonly ConcurrentDictionary _loggers = new(); @@ -35,20 +75,14 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except logAction.Invoke(categoryName, logLevel, exception, msg); } - public bool IsEnabled(LogLevel logLevel) - { - return true; - } + public bool IsEnabled(LogLevel logLevel) => true; #if NET7_0_OR_GREATER IDisposable? #else IDisposable #endif - ILogger.BeginScope(TState state) - { - return NullScope.Instance; - } + ILogger.BeginScope(TState state) => NullScope.Instance; } }