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 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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With