简体   繁体   English

如何使用ASP.NET Core日志记录懒惰?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM