Skip to content

Commit

Permalink
Adding LoggingBehavior
Browse files Browse the repository at this point in the history
  • Loading branch information
ardalis committed Aug 1, 2023
1 parent c86329b commit 93d0ae9
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 3 deletions.
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
<Project>
<ItemGroup>
<PackageVersion Include="Ardalis.GuardClauses" Version="4.1.1" />
<PackageVersion Include="Ardalis.Specification" Version="7.0.0" />
<PackageVersion Include="coverlet.collector" Version="3.2.0" />
<PackageVersion Include="FluentAssertions" Version="6.11.0" />
<PackageVersion Include="MediatR" Version="12.1.1" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageVersion Include="Moq" Version="4.18.4" />
<PackageVersion Include="xunit" Version="2.4.2" />
Expand Down
6 changes: 4 additions & 2 deletions src/Ardalis.SharedKernel/Ardalis.SharedKernel.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
<RepositoryUrl>https://github.com/ardalis/Ardalis.SharedKernel</RepositoryUrl>
<PackageTags>DDD;Shared Kernel;SharedKernel;Domain-Driven Design;Repository;Specification;ValueObject;Value Object;Ardalis;Clean;Clean Architecture;Clean Architecture Template</PackageTags>
<PackageIcon>icon.png</PackageIcon>
<Version>1.2.0</Version>
<Version>1.3.0</Version>
<PackageReleaseNotes>
* Add Commands, Queries, and Handler interfaces
* Adding LoggingBehavior
</PackageReleaseNotes>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
Expand All @@ -24,8 +24,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Ardalis.GuardClauses" />
<PackageReference Include="Ardalis.Specification" />
<PackageReference Include="MediatR" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>

<ItemGroup>
Expand Down
63 changes: 63 additions & 0 deletions src/Ardalis.SharedKernel/LoggingBehavior.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System.Diagnostics;
using System.Reflection;
using Ardalis.GuardClauses;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Ardalis.SharedKernel;

/// <summary>
/// Adds logging for all requests in MediatR pipeline.
/// Configure by adding the service with a scoped lifetime
///
/// Example for Autofac:
/// builder
/// .RegisterType&lt;Mediator&gt;()
/// .As&lt;IMediator&gt;()
/// .InstancePerLifetimeScope();
///
/// builder
/// .RegisterGeneric(typeof(LoggingBehavior&lt;,&gt;))
/// .As(typeof(IPipelineBehavior&lt;,&gt;))
/// .InstancePerLifetimeScope();
///
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly ILogger<Mediator> _logger;

public LoggingBehavior(ILogger<Mediator> logger)
{
_logger = logger;
}

public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
Guard.Against.Null(request);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Handling {RequestName}", typeof(TRequest).Name);

// Reflection! Could be a performance concern
Type myType = request.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
object? propValue = prop?.GetValue(request, null);
_logger.LogInformation("Property {Property} : {@Value}", prop?.Name, propValue);
}
}

var sw = Stopwatch.StartNew();

var response = await next();

_logger.LogInformation("Handled {RequestName} with {Response} in {ms} ms", typeof(TRequest).Name, response, sw.ElapsedMilliseconds);
sw.Stop();
return response;
}
}

4 changes: 3 additions & 1 deletion src/Ardalis.SharedKernel/MediatRDomainEventDispatcher.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using MediatR;
using System;
using MediatR;

namespace Ardalis.SharedKernel;

Expand All @@ -24,3 +25,4 @@ public async Task DispatchAndClearEvents(IEnumerable<EntityBase> entitiesWithEve
}
}
}

0 comments on commit 93d0ae9

Please sign in to comment.