Skip to content

Commit

Permalink
feat: add logging behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikoo-Asadnejad committed May 3, 2024
1 parent b7f1045 commit f3653f7
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 2 deletions.
6 changes: 6 additions & 0 deletions Src/Product.API/Controllers/ProductController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Product.API.Controllers;

public sealed class ProductController
{

}
2 changes: 1 addition & 1 deletion Src/Product.API/Product.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
</ItemGroup>

<ItemGroup>
<Folder Include="Controllers" />
<Folder Include="Middlewares\" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Product.Application.Product.Queries.GetProduct;

public class GetProductQueryHandler : IRequestHandler<GetProductQuery ,GetProductQueryResponse>
public sealed class GetProductQueryHandler : IRequestHandler<GetProductQuery ,GetProductQueryResponse>
{
public Task<GetProductQueryResponse> Handle(GetProductQuery request, CancellationToken cancellationToken)
{
Expand Down
28 changes: 28 additions & 0 deletions Src/Product.Application/Shared/Behaviors/LoggingBehavior.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using MediatR;
using Microsoft.Extensions.Logging;

namespace Product.Application.Shared.Behaviors;

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

public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
try
{
return await next();
}
catch (Exception ex)
{
_logger.LogError(ex.Message, ex);
throw;
}
}
}
1 change: 1 addition & 0 deletions Src/Product.Ioc/Ioc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public static void InjectServices(this IServiceCollection services , Assembly as
{
config.RegisterServicesFromAssembly(assembly);
config.AddOpenBehavior(typeof(ValidationBehavior<,>));
config.AddBehavior(typeof(LoggingBehavior<,>));
});
}
}

0 comments on commit f3653f7

Please sign in to comment.