How to record with ASP.NET Core logging?

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 case, the call LogInformation

will call the call string.Format

, and worse, the line LogTrace

will call aSerializeObject

LogLevel

call , regardless . That seems pretty wasteful.

Is there a place in the registration API that allows for a lazier approach? The only workaround I can think of is overriding ToString

on the model to create a very detailed view and skip using JsonConvert.SerializeObject

as a tool.

+3


source to share


1 answer


The interface ILogger

provides a method 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));
}

      



You will find the default implementation on GitHub: https://github.com/aspnet/Extensions/blob/master/src/Logging/Logging/src/Logger.cs#L53

+5


source







All Articles