Skip to content

Commit

Permalink
feat: update DelegateLoggerProvider
Browse files Browse the repository at this point in the history
  • Loading branch information
WeihanLi committed Jul 8, 2024
1 parent f558700 commit 4754995
Showing 1 changed file with 43 additions and 9 deletions.
52 changes: 43 additions & 9 deletions src/WeihanLi.Common/Logging/MicrosoftLoggingLoggerExtensions.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -12,7 +14,45 @@ public sealed class DelegateLoggerProvider(Action<string, LogLevel, Exception?,
{
internal static ILoggerProvider Default { get; } = new DelegateLoggerProvider((category, level, exception, msg) =>
{
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<string, DelegateLogger> _loggers = new();
Expand All @@ -35,20 +75,14 @@ public void Log<TState>(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>(TState state)
{
return NullScope.Instance;
}
ILogger.BeginScope<TState>(TState state) => NullScope.Instance;
}
}

Expand Down

0 comments on commit 4754995

Please sign in to comment.