How to log lazily with ASP.NET Core logging?

1.1k views Asked by At

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.

1

There are 1 answers

0
meziantou On BEST ANSWER

The ILogger interface provides the IsEnabled method:

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