Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log lazily 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 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.

like image 835
Jeroen Avatar asked May 28 '17 13:05

Jeroen


People also ask

What is the use of ILogger in .NET Core?

The ILoggerFactory is the factory interface for creating an appropriate ILogger type instance and also for adding the ILoggerProvider instance. The Logging API includes the built-in LoggerFactory class that implements the ILoggerFactory interface.

Where does the log file get written to in .NET Core logging?

ILogger : This interface provides the Log() method, which can be used to write a log message. ILoggerProvider : Logging providers implement this interface to write the logs to a specific destination. For example, the Console ILoggerProvider writes the logs to the console.

Which .NET function would you use to get a logger?

log4net is one of the most common external logging services available to . NET developers. The developers for log4net promise you can have logging integrated with your application within minutes, and it's true—setup is easy. log4net is available in NuGet, so it's just as easy to install as it is to code.


1 Answers

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

like image 167
meziantou Avatar answered Oct 26 '22 23:10

meziantou