Skip to content

Latest commit

 

History

History
49 lines (35 loc) · 1.58 KB

logging-behavior.md

File metadata and controls

49 lines (35 loc) · 1.58 KB
description
Logging behavior in the MediatR pipeline within RCommon.

Logging Behavior

The logging behavior is useful any time you want to log an incoming request in the MediatR pipeline.

Implementation

public class LoggingRequestBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest
{
    private readonly ILogger<LoggingRequestBehavior<TRequest, TResponse>> _logger;
    public LoggingRequestBehavior(ILogger<LoggingRequestBehavior<TRequest, TResponse>> logger) => _logger = logger;


    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        _logger.LogInformation("----- Handling command {CommandName} ({@Command})", request.GetGenericTypeName(), request);
        var response = await next();
        _logger.LogInformation("----- Command {CommandName} handled - response: {@Response}", request.GetGenericTypeName(), response);

        return response;
    }
}

Usage

builder.Services.AddRCommon()
    .WithMediator<MediatRBuilder>(mediator =>
    {
        // Conventional dependency injection w/ MediatR
        mediator.Configure(config =>
        {
            config.RegisterServicesFromAssemblies((typeof(ApplicationServicesRegistration).GetTypeInfo().Assembly));
        });
        
        // Utilizing MediatR pipeline registrations
        mediator.AddLoggingToRequestPipeline();
    });