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
. That seems rather wasteful.
Is there a place in the Logging API that allows for a more lazy approach? 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.
The
ILogger
interface provides theIsEnabled
method:You'll find the default implementation on GitHub: https://github.com/aspnet/Extensions/blob/master/src/Logging/Logging/src/Logger.cs#L53