c# - 如何使用 ASP.NET Core 日志记录延迟记录?

标签 c# .net-core .net-core-logging

假设这样的场景:

[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; } 
}

在这种情况下,LogInformation调用将触发 string.Format打电话,更糟糕的是,LogTrace行将触发 一个 SerializeObject打电话,不管LogLevel .这似乎相当浪费。

Logging API 中是否有允许更懒惰的方法的地方?我能想到的唯一解决方法是覆盖 ToString在模型上创建一个非常详细的表示,并跳过使用 JsonConvert.SerializeObject作为工具。

最佳答案

ILogger接口(interface)提供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));
}

您将在 GitHub 上找到默认实现:https://github.com/aspnet/Extensions/blob/master/src/Logging/Logging/src/Logger.cs#L53

关于c# - 如何使用 ASP.NET Core 日志记录延迟记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44227712/

相关文章:

c# - Log4Net/C# - 禁用默认日志记录

c# - 按日期时间间隔对对象进行分组

active-directory - 在 .NET Core 1.0 应用程序中针对 Active Directory 进行身份验证?

.net-core - Serilog Splunk 不记录消息

.net-core-logging - 如何在 .NET Core 3 中通过命令行参数设置日志级别

.net-core - netcore2 控制台应用程序在 appsettings 配置日志级别

c# - 如何让ffmpeg.exe解决输入帧序列的fps不一致问题?

c# - 在 C# 和 XAML 中提取 Key 的内容值

c# - 在永远不会重新分配字段的情况下,复制方法主体中字段的引用以读取它有什么好处?

c# - 大字典的递归函数导致堆栈溢出问题