给微软的日志框架写一个基于委托的日志提供者
动手造轮子:给微软的日志框架写一个基于委托的日志提供者
动手造轮子:给微软的日志框架写一个基于委托的日志提供者
Intro
微软的日志框架现在已经比较通用,有时候我们不想使用外部的日志提供者,但又希望提供一个比较简单的委托就可以实现日志记录,于是就有了后面的探索和实现。
Solution
基于委托的 LoggerProvider
实现代码:
[ProviderAlias("Delegate")]
public class DelegateLoggerProvider : ILoggerProvider
{
private readonly Action<string, LogLevel, Exception, string> _logAction;
private readonly ConcurrentDictionary<string, DelegateLogger> _loggers = new ConcurrentDictionary<string, DelegateLogger>();
public DelegateLoggerProvider(Action<string, LogLevel, Exception, string> logAction)
{
_logAction = logAction;
}
public void Dispose()
{
_loggers.Clear();
}
public ILogger CreateLogger(string categoryName)
{
return _loggers.GetOrAdd(categoryName, category => new DelegateLogger(category, _logAction));
}
private class DelegateLogger : ILogger
{
private readonly string _categoryName;
private readonly Action<string, LogLevel, Exception, string> _logAction;
public DelegateLogger(string categoryName, Action<string, LogLevel, Exception, string> logAction)
{
_categoryName = categoryName;
_logAction = logAction;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (null != _logAction)
{
var msg = formatter(state, exception);
_logAction.Invoke(_categoryName, logLevel, exception, msg);
}
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public IDisposable BeginScope<TState>(TState state)
{
return NullScope.Instance;
}
}
}
使用示例
ILoggerFactory loggerFactory = new LoggerFactory();
//loggerFactory.AddConsole();
loggerFactory.AddDelegateLogger(
(category, logLevel, exception, msg) =>
{
Console.WriteLine($"{category}:[{logLevel}] {msg}\n{exception}");
}
);
日志输出效果如下:
Reference
版权声明:本文为weihanli原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。