2017-05-28 68 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

回答