mon*_*nty 10 .net-core asp.net-core asp.net-core-2.1
在我的项目中,我经常在日志消息中添加前缀。
目前我正在这样做
logger.LogDebug(prefix + " some message");
Run Code Online (Sandbox Code Playgroud)
我认为这将是实现自定义记录器的好方法,我在其中设置前缀,并且记录器本身在每次记录某些内容时都会附加它。
所以我创建了我的自定义记录器类并实现了 ILogger 接口。但我不明白如何使用
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
Run Code Online (Sandbox Code Playgroud)
添加前缀的方法(它是自定义记录器类的成员)。
我的完整代码是:
public class CustomLogger : ILogger
{
private readonly ILogger _logger;
private string _logPrefix;
public CustomLogger(ILogger logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_logPrefix = null;
}
public ILogger SetLogPrefix(string logPrefix)
{
_logPrefix = logPrefix;
return this;
}
public IDisposable BeginScope<TState>(TState state)
{
return _logger.BeginScope(state);
}
public bool IsEnabled(LogLevel logLevel)
{
return _logger.IsEnabled(logLevel);
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
_logger.Log(logLevel, eventId, state, exception, formatter);
}
}
Run Code Online (Sandbox Code Playgroud)
Kha*_*yen 10
我认为您不应该在自定义记录器中调用 _logger。
这将是运行时的循环调用,结果将是“前缀:前缀:前缀:前缀:前缀:前缀:前缀:前缀:...”
简单来说,你可以创建一个简单的记录器并实现一个日志编写器,如控制台、数据库编写器、log4net、...
现在首先,您应该像下面这样更改您的自定义记录器:
public class CustomLogger : ILogger
{
private readonly string CategoryName;
private readonly string _logPrefix;
public CustomLogger(string categoryName, string logPrefix)
{
CategoryName = categoryName;
_logPrefix = logPrefix;
}
public IDisposable BeginScope<TState>(TState state)
{
return new NoopDisposable();
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
string message = _logPrefix;
if (formatter != null)
{
message += formatter(state, exception);
}
// Implement log writter as you want. I am using Console
Console.WriteLine($"{logLevel.ToString()} - {eventId.Id} - {CategoryName} - {message}");
}
private class NoopDisposable : IDisposable
{
public void Dispose()
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
第二步,创建一个logger provider:
public class LoggerProvider : ILoggerProvider
{
public ILogger CreateLogger(string categoryName)
{
return new CustomLogger(categoryName, "This is prefix: ");
}
public void Dispose()
{
}
}
Run Code Online (Sandbox Code Playgroud)
第三步,在从 Startup.cs 配置:
loggerFactory.AddProvider(new MicroserviceLoggerProvider());
Run Code Online (Sandbox Code Playgroud)
就个人而言,我认为这不是一个好方法,“前缀”会重复很多。为什么不改用日志范围?
public IActionResult GetById(string id)
{
TodoItem item;
using (_logger.BeginScope("Message attached to logs created in the using block"))
{
_logger.LogInformation(LoggingEvents.GetItem, "Getting item {ID}", id);
item = _todoRepository.Find(id);
if (item == null)
{
_logger.LogWarning(LoggingEvents.GetItemNotFound, "GetById({ID}) NOT FOUND", id);
return NotFound();
}
}
return new ObjectResult(item);
}
Run Code Online (Sandbox Code Playgroud)
输出
info: TodoApi.Controllers.TodoController[1002]
=> RequestId:0HKV9C49II9CK RequestPath:/api/todo/0 => TodoApi.Controllers.TodoController.GetById (TodoApi) => Message attached to logs created in the using block
Getting item 0
warn: TodoApi.Controllers.TodoController[4000]
=> RequestId:0HKV9C49II9CK RequestPath:/api/todo/0 => TodoApi.Controllers.TodoController.GetById (TodoApi) => Message attached to logs created in the using block
GetById(0) NOT FOUND
Run Code Online (Sandbox Code Playgroud)
目前,您无法更改日志记录模板,这是 Asp.net Core 内置基本日志记录的限制。对于更强大的,您可以尝试Serilog,继续使用ILogger接口并更改program.cs类中的一些代码行
您还应该查看结构化日志记录与基本日志记录的好处
| 归档时间: |
|
| 查看次数: |
12455 次 |
| 最近记录: |