Created
September 21, 2023 08:29
-
-
Save havarnov/ca3020a89cd77b7cca6dfc67ab07f6e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using AspectCore.Configuration; | |
using AspectCore.DynamicProxy; | |
using Microsoft.Extensions.Logging; | |
var loggerFactory = LoggerFactory.Create(c => c.AddSimpleConsole()); | |
var generator = new ProxyGeneratorBuilder() | |
.Configure(c => | |
{ | |
c.Interceptors.Add( | |
new TypeInterceptorFactory( | |
typeof(LoggerInterceptor), | |
new object[] { loggerFactory.CreateLogger("Foo") })); | |
}) | |
.Build(); | |
var actual = new Foo(loggerFactory.CreateLogger<Foo>()); | |
var proxiedService = generator.CreateInterfaceProxy<IFoo>(actual); | |
await proxiedService.Bar(42); | |
public class LoggerInterceptor : AbstractInterceptor | |
{ | |
private readonly ILogger _logger; | |
public LoggerInterceptor(ILogger logger) | |
{ | |
_logger = logger; | |
} | |
public override async Task Invoke(AspectContext context, AspectDelegate next) | |
{ | |
var parameters = string.Join(", ", context.Parameters); | |
_logger.LogInformation("START: {MethodName}: {Parameters}", context.ProxyMethod.Name, parameters); | |
await next(context); // Run the function | |
_logger.LogInformation("END: "); | |
} | |
} | |
public interface IFoo | |
{ | |
Task<int> Bar(int input); | |
} | |
class Foo : IFoo | |
{ | |
private readonly ILogger<Foo> _logger; | |
public Foo(ILogger<Foo> logger) | |
{ | |
_logger = logger; | |
} | |
public async Task<int> Bar(int input) | |
{ | |
_logger.LogInformation("INSIDE: Foo.Bar (start)"); | |
await Task.Delay(TimeSpan.FromSeconds(1)); | |
var result = input * 2; | |
_logger.LogInformation("INSIDE: Foo.Bar (end): {Result}", result); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment