-
Notifications
You must be signed in to change notification settings - Fork 62
feat(logger): ILogger 支持 #2447
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat(logger): ILogger 支持 #2447
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
881f38e
feat(logger): ILogger 支持
tangge233 00c4c23
chore: upd deps
tangge233 ac916a3
chore: apply suggestions from rider
tangge233 cb8f9e1
chore: add global static logger factory
tangge233 07ba16d
chore: readonly
tangge233 9b57ffc
Update PCL.Core/Logging/LogWrapper.cs
tangge233 891db63
revert: use field
tangge233 6b33f51
chore: apply suggestions
tangge233 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| using Microsoft.Extensions.Logging; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Text; | ||
| using System.Threading; | ||
|
|
||
| namespace PCL.Core.Logging; | ||
|
|
||
| /// <summary> | ||
| /// Microsoft.Extensions.Logging.ILogger 适配器 | ||
| /// 将现有的 Logger 包装为标准的 ILogger 接口实现 | ||
| /// </summary> | ||
| public class LoggerAdapter(Logger logger, string categoryName) : ILogger | ||
| { | ||
| private readonly Logger _innerLogger = logger ?? throw new ArgumentNullException(nameof(logger)); | ||
| private readonly string _categoryName = categoryName ?? throw new ArgumentNullException(nameof(categoryName)); | ||
|
|
||
| private static readonly AsyncLocal<Stack<object>> _ScopeStack = new(); | ||
|
|
||
| IDisposable ILogger.BeginScope<TState>(TState state) | ||
| { | ||
| _ScopeStack.Value ??= new Stack<object>(); | ||
| _ScopeStack.Value.Push(state); | ||
| return new ScopeDisposable(state); | ||
| } | ||
|
|
||
| #pragma warning disable CS9113 // 参数未读。 | ||
| private class ScopeDisposable(object state) : IDisposable | ||
| { | ||
| private bool _disposed; | ||
|
|
||
| public void Dispose() | ||
| { | ||
| if (_disposed) | ||
| return; | ||
|
|
||
| if (_ScopeStack.Value is { Count: > 0 }) | ||
| { | ||
| #if DEBUG | ||
| var popped = _ScopeStack.Value.Pop(); | ||
| if (!ReferenceEquals(popped, state)) | ||
| { | ||
| throw new InvalidOperationException("Scope disposal order mismatch."); | ||
| } | ||
| #else | ||
| _ = _ScopeStack.Value.Pop(); | ||
| #endif | ||
| } | ||
|
|
||
| _disposed = true; | ||
| } | ||
| } | ||
|
|
||
| public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel level) => true; | ||
|
|
||
| public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) | ||
| { | ||
| if (!IsEnabled(logLevel)) | ||
| return; | ||
|
|
||
| ArgumentNullException.ThrowIfNull(formatter); | ||
|
|
||
| var originalMessage = formatter(state, exception); | ||
| var sb = new StringBuilder(); | ||
|
|
||
| // 类别名称 | ||
| if (!string.IsNullOrEmpty(_categoryName)) | ||
| { | ||
| sb.Append('[').Append(_categoryName).Append("] "); | ||
| } | ||
|
|
||
| // 事件 ID | ||
| if (eventId.Id != 0 || !string.IsNullOrEmpty(eventId.Name)) | ||
| { | ||
| sb.Append("[EventId:"); | ||
| if (!string.IsNullOrEmpty(eventId.Name)) | ||
| { | ||
| sb.Append(eventId.Id).Append(':').Append(eventId.Name); | ||
| } | ||
| else | ||
| { | ||
| sb.Append(eventId.Id); | ||
| } | ||
| sb.Append("] "); | ||
| } | ||
|
|
||
| // 上下文信息 | ||
| var scopeContext = _BuildScopeContext(); | ||
| if (!string.IsNullOrEmpty(scopeContext)) | ||
| { | ||
| sb.Append('[').Append(_categoryName).Append("] "); | ||
| } | ||
|
|
||
| sb.Append(originalMessage); | ||
| var finalMessage = sb.ToString(); | ||
|
|
||
| // 日志级别 | ||
| switch (logLevel) | ||
| { | ||
| case Microsoft.Extensions.Logging.LogLevel.Trace: | ||
| _innerLogger.Trace(finalMessage); | ||
| break; | ||
| case Microsoft.Extensions.Logging.LogLevel.Debug: | ||
| _innerLogger.Debug(finalMessage); | ||
| break; | ||
| case Microsoft.Extensions.Logging.LogLevel.Information: | ||
| _innerLogger.Info(finalMessage); | ||
| break; | ||
| case Microsoft.Extensions.Logging.LogLevel.Warning: | ||
| _innerLogger.Warn(finalMessage); | ||
| break; | ||
| case Microsoft.Extensions.Logging.LogLevel.Error: | ||
| _innerLogger.Error(finalMessage); | ||
| break; | ||
| case Microsoft.Extensions.Logging.LogLevel.Critical: | ||
| _innerLogger.Fatal(finalMessage); | ||
| break; | ||
| } | ||
|
|
||
| if (exception != null) | ||
| { | ||
| var exceptionMessage = $"Exception: {exception}"; | ||
| _innerLogger.Log($"[{_categoryName}] {exceptionMessage}"); | ||
| } | ||
| } | ||
|
|
||
| private string _BuildScopeContext() | ||
| { | ||
| var stack = _ScopeStack.Value; | ||
| if (stack == null || stack.Count == 0) | ||
| return string.Empty; | ||
|
|
||
| var scopes = stack.AsEnumerable().Reverse(); | ||
| return string.Join(" => ", scopes.Select(s => s.ToString())); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| using System; | ||
| using System.Diagnostics; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace PCL.Core.Logging; | ||
|
|
||
| public static class LoggerExtensions | ||
| { | ||
| /// <summary> | ||
| /// 创建 ILogger 实例 | ||
| /// </summary> | ||
| /// <param name="logger">现有的 Logger 实例</param> | ||
| /// <param name="categoryName">日志类别名称</param> | ||
| /// <returns>ILogger 实例</returns> | ||
| public static ILogger CreateLogger(this Logger logger, string categoryName) | ||
| { | ||
| return new LoggerAdapter(logger, categoryName); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// 创建 ILogger 工厂 | ||
| /// </summary> | ||
| /// <param name="logger">现有的 Logger 实例</param> | ||
| /// <returns>ILoggerFactory 实例</returns> | ||
| public static ILoggerFactory CreateLoggerFactory(this Logger logger) | ||
| { | ||
| return new LoggerFactoryAdapter(logger); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// 使用结构化日志记录的扩展方法 | ||
| /// </summary> | ||
| public static void LogInformation<T0>(this ILogger logger, string message, T0 arg0) | ||
| { | ||
| logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, message, arg0); | ||
| } | ||
|
|
||
| public static void LogInformation<T0, T1>(this ILogger logger, string message, T0 arg0, T1 arg1) | ||
| { | ||
| logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, message, arg0, arg1); | ||
| } | ||
|
|
||
| public static void LogInformation<T0, T1, T2>(this ILogger logger, string message, T0 arg0, T1 arg1, T2 arg2) | ||
| { | ||
| logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, message, arg0, arg1, arg2); | ||
| } | ||
|
|
||
| public static void LogWarning<T0>(this ILogger logger, string message, T0 arg0) | ||
| { | ||
| logger.Log(Microsoft.Extensions.Logging.LogLevel.Warning, message, arg0); | ||
| } | ||
|
|
||
| public static void LogWarning<T0, T1>(this ILogger logger, string message, T0 arg0, T1 arg1) | ||
| { | ||
| logger.Log(Microsoft.Extensions.Logging.LogLevel.Warning, message, arg0, arg1); | ||
| } | ||
|
|
||
| public static void LogError<T0>(this ILogger logger, Exception? exception, string message, T0 arg0) | ||
| { | ||
| logger.Log(Microsoft.Extensions.Logging.LogLevel.Error, exception, message, arg0); | ||
| } | ||
|
|
||
| public static void LogError<T0, T1>(this ILogger logger, Exception? exception, string message, T0 arg0, T1 arg1) | ||
| { | ||
| logger.Log(Microsoft.Extensions.Logging.LogLevel.Error, exception, message, arg0, arg1); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// 条件日志记录扩展方法 | ||
| /// </summary> | ||
| public static void LogIf(this ILogger logger, bool condition, Microsoft.Extensions.Logging.LogLevel level, string message) | ||
| { | ||
| if (condition) | ||
| { | ||
| logger.Log(level, message); | ||
| } | ||
| } | ||
|
|
||
| public static void LogIf(this ILogger logger, bool condition, Microsoft.Extensions.Logging.LogLevel level, Exception? exception, string message) | ||
| { | ||
| if (condition) | ||
| { | ||
| logger.Log(level, exception, message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// 性能计时日志记录 | ||
| /// </summary> | ||
| public static IDisposable LogPerformance(this ILogger logger, string operationName) | ||
| { | ||
| logger.LogInformation("开始执行: {OperationName}", operationName); | ||
|
|
||
| return new PerformanceLoggerDisposable(logger, operationName); | ||
| } | ||
|
|
||
| private class PerformanceLoggerDisposable(ILogger logger, string operationName) : IDisposable | ||
| { | ||
| private readonly long _startTime = Stopwatch.GetTimestamp(); | ||
|
|
||
| public void Dispose() | ||
| { | ||
| var elapsed = Stopwatch.GetElapsedTime(_startTime); | ||
| logger.LogInformation("完成执行: {OperationName}, 耗时: {ElapsedMs}ms", operationName, elapsed.TotalMilliseconds); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| using Microsoft.Extensions.Logging; | ||
| using System; | ||
| using System.Collections.Generic; | ||
|
|
||
| namespace PCL.Core.Logging; | ||
|
|
||
| /// <summary> | ||
| /// ILoggerFactory 实现,用于创建 LoggerAdapter 实例 | ||
| /// </summary> | ||
| public class LoggerFactoryAdapter(Logger logger) : ILoggerFactory | ||
| { | ||
| private readonly Logger _logger = logger ?? throw new ArgumentNullException(nameof(logger)); | ||
| private readonly List<IDisposable> _disposables = []; | ||
|
|
||
| public void AddProvider(ILoggerProvider provider) | ||
| { | ||
| _disposables.Add(provider); | ||
| // 不需要实现,因为我们只有一个固定的 Logger | ||
| } | ||
|
|
||
| public ILogger CreateLogger(string categoryName) | ||
| { | ||
| return new LoggerAdapter(_logger, categoryName); | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| foreach (var disposable in _disposables) | ||
| { | ||
| disposable.Dispose(); | ||
| } | ||
| _disposables.Clear(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.