[英]How to log lazily with ASP.NET Core logging?
Suppose a scenario like this: 假设这样的场景:
[Route("api/test")]
public class TestController
{
private readonly ILogger<TestController> logger;
public TestController(ILogger<TestController> logger)
{
this.logger = logger;
}
[HttpPut]
public void Put(Guid id, [FromBody]FooModel model)
{
logger.LogInformation($"Putting {id}");
logger.LogTrace("Putting model {0}", Newtonsoft.Json.JsonConvert.SerializeObject(model));
try
{
// Omitted: actual PUT operation.
}
catch (Exception ex)
{
logger.LogError("Exception {0}", ex);
}
}
}
public class FooModel
{
string Bar { get; set; }
}
In this scenario, the LogInformation
call will trigger a string.Format
call, and even worse, the LogTrace
line will trigger a SerializeObject
call, regardless of the LogLevel
. 在这种情况下,
LogInformation
调用将触发string.Format
调用,更糟糕的是,无论LogLevel
如何, LogTrace
行都将触发SerializeObject
调用 。 That seems rather wasteful. 这似乎相当浪费。
Is there a place in the Logging API that allows for a more lazy approach? Logging API中是否存在允许更懒惰的方法? The only workaround I can think of is overriding
ToString
on model to create a very verbose representation, and skip on using JsonConvert.SerializeObject
as a tool. 我能想到的唯一解决方法是在模型上覆盖
ToString
以创建非常详细的表示,并跳过使用JsonConvert.SerializeObject
作为工具。
The ILogger
interface provides the IsEnabled
method: ILogger
接口提供IsEnabled
方法:
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation($"Putting {id}");
}
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Putting model {0}", Newtonsoft.Json.JsonConvert.SerializeObject(model));
}
You'll find the default implementation on GitHub: https://github.com/aspnet/Extensions/blob/master/src/Logging/Logging/src/Logger.cs#L53 你会在GitHub上找到默认的实现: https : //github.com/aspnet/Extensions/blob/master/src/Logging/Logging/src/Logger.cs#L53
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.