2017-05-28 40 views
3

假设的场景是这样的:如何用ASP.NET Core日志记录懒惰地登录?

[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作为工具。

+0

下面是一个使用'IsEnabled' http://dotnetliberty.com/文章index.php/2015/11/19/asp-net-5-why-use-ilogger-isenabled/ – Svek

+0

如果这不是您要查找的内容,您的意思是您仍然希望记录发生但不是原因主线延迟? – Svek

+0

啊,不,这篇文章以及@ meziantou的答案似乎是我想要的,尽管我仍在思考如何防止在任何地方重复这个问题。基本上我在寻找例如API允许我将'Logger.IsEnabled(...)'和'Logger.LogTrace(...)'调用结合起来。 – Jeroen

回答