We've seen earlier how we can write custom middleware to perform actions before and after the rest of the pipeline. A simple middleware class to log all requests can be written as follows:
public class LoggingMiddleware { private readonly RequestDelegate _next; private readonly ILoggerFactory _loggerFactory; public LoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) { this._next = next; this._loggerFactory = loggerFactory; } public async Task Invoke(HttpContext context) { var logger = this._loggerFactory.CreateLogger<LoggingMiddleware>(); using (logger.BeginScope<LoggingMiddleware>(this)) { logger.LogInformation("Before request"); await this._next.Invoke(context); logger.LogInformation("After request"); } } }
Notice that the category of the logger is set to the LoggingMiddleware
type's full name and we are starting a scope for each invocation, which is here just as an example...