Skip to content
This repository was archived by the owner on Apr 11, 2024. It is now read-only.

Commit 0ac94ec

Browse files
committed
feat(enrolling): enable logging every command and query processing
1 parent 70114d7 commit 0ac94ec

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using System.Threading;
2+
using System.Threading.Tasks;
3+
using MediatR;
4+
using Microsoft.Extensions.Logging;
5+
6+
namespace OpenCodeFoundation.ESchool.Services.Enrolling.API.Application.Behaviors
7+
{
8+
public class LoggingBehavior<TRequest, TResponse>
9+
: IPipelineBehavior<TRequest, TResponse>
10+
{
11+
private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
12+
13+
public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
14+
{
15+
_logger = logger ?? throw new System.ArgumentNullException(nameof(logger));
16+
}
17+
18+
public async Task<TResponse> Handle(
19+
TRequest request,
20+
CancellationToken cancellationToken,
21+
RequestHandlerDelegate<TResponse> next)
22+
{
23+
_logger.LogInformation(
24+
"Handling request {RequestName} ({@Request})",
25+
request.GetType().Name,
26+
request);
27+
28+
var response = await next();
29+
30+
_logger.LogInformation(
31+
"Request {RequestName} handled. Response: {@Response}",
32+
request.GetType().Name,
33+
response);
34+
35+
return response;
36+
}
37+
}
38+
}

src/Services/Enrolling/Enrolling.API/Startup.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
using Microsoft.Extensions.DependencyInjection;
1212
using Microsoft.Extensions.Hosting;
1313
using Microsoft.OpenApi.Models;
14+
using OpenCodeFoundation.ESchool.Services.Enrolling.API.Application.Behaviors;
1415
using OpenCodeFoundation.ESchool.Services.Enrolling.API.Application.Validations;
1516
using OpenCodeFoundation.ESchool.Services.Enrolling.API.Extensions;
1617
using OpenCodeFoundation.ESchool.Services.Enrolling.Infrastructure;
@@ -31,6 +32,8 @@ public void ConfigureServices(IServiceCollection services)
3132
{
3233
services.AddMediatR(typeof(Startup).GetTypeInfo().Assembly);
3334

35+
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
36+
3437
services.AddDbContext<EnrollingContext>(options =>
3538
{
3639
options.UseSqlServer(

0 commit comments

Comments
 (0)