The logging infrastructure is already registered in the built-in dependency injection container, so all you need to do to get access to the logger is to add it as a parameter in your controller constructor so that it will be injected when the controller is created. For example, this is how the logger is injected into the GiveNTake ProductsController:
using Microsoft.Extensions.Logging;
[Authorize]
[Route("api/[controller]")]
public class ProductsController : Controller
{
...
private readonly ILogger<ProductsController> _logger;
public ProductsController(GiveNTakeContext context, ILogger<ProductsController> logger)
{
_logger = logger;
...
}
...
}
Whenever you need to write a log event, you need to use one of the ILogger Log[Level] methods, where level can be Trace, Debug, Information, Warning, Error, or Critical. These methods are extension methods to the ILogger interface that simply wrap the call to the generic Log method.
For example, the action for searching by category validates that the client provided a value for the category parameter, and if not, responds with a BadRequest. It will be helpful for us to write a log event of a warning so that we can later check why the user request has failed:
[AllowAnonymous]
[HttpGet("searchcategory/{category}/{subcategory=all}/")]
public async Task<ActionResult<ProductDTO[]>> SearchByCategory(string category,
string subcategory,
string location = "all",
bool imageOnly = false)
{
if (string.IsNullOrEmpty(category))
{
_logger.LogWarning("An empty category was sent from the client. SubCategory: '{SubCategory}', Location: '{Location}'", subcategory, location);
return BadRequest();
}
...
}
The logging method has a few overloads (that vary based on the level) and their signature looks roughly like what's shown in the following screenshot:
The parameters in the preceding screenshot are defined as follows:
- eventId (optional): A value (usually an integer) that represents a logical event in the application. This can be helpful for grouping various messages that belong to the same logical context.
- exception (optional): The exception that represents the error that is being logged.
- message: The message to be logged. It can contain placeholders for formatted arguments in the form {argument}. The arguments are placed based on position, and not on content.
- args: A collection of arguments placed inside the formatted message to be delivered to the logging provider for storage.
Run the application and perform a request to the SearchByCategory action without passing a category to see the log message in the output window:
You can see that, besides the log event that you've written in the controller, other logs are written from other areas in the request pipeline. As useful as they may be, they can be distracting, and therefore, it's worthwhile to have the ability to filter log events by certain conditions.