在 .NET Core 2.1 中使用 AOP 进行日志记录 [英] Logging using AOP in .NET Core 2.1

查看:144
本文介绍了在 .NET Core 2.1 中使用 AOP 进行日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 .NET Core 2.1 解决方案中为日志实现 AOP.我以前从未使用过它,而且我一直在网上查找,似乎看不到任何人将它与 Core 2 一起使用的示例.有谁知道我会怎么做?

I want to implement AOP for the logging in my .NET Core 2.1 solution. I've never used it before and I've been looking online and cant seem to see any examples of people using it with Core 2. Does anyone know how i would go about this?

例如,用于 AOP 的包以及有任何示例代码可以帮助我入门?我使用内置 DI 和 .net 核心,所以我不需要担心那部分.

For example what packages to use for AOP and have any example code to get me started? Im using the built in DI with .net core so i dont need to worry about that part.

推荐答案

Microsoft DI 不提供诸如拦截器或装饰器之类的高级方案(使用 Microsoft DI 的装饰器有一个解决方法:https://medium.com/@willie.tetlow/net-core-dependency-injection-decorator-workaround-664cd3ec1246).

Microsoft DI does not offer advances scenarios such as interceptor or decorators(there is a workaround for decorators using Microsoft DI: https://medium.com/@willie.tetlow/net-core-dependency-injection-decorator-workaround-664cd3ec1246).

您可以使用 Autofac (https://autofaccn.readthedocs.io/en/latest/advanced/interceptors.html) 或带有动态代理的简单注入器.两者都有非常好的文档.简单的注入器由于其设计规则而没有开箱即用的拦截解决方案,但您可以为其添加扩展(http://simpleinjector.readthedocs.io/en/latest/aop.html).

You can implement AOP by using Autofac (https://autofaccn.readthedocs.io/en/latest/advanced/interceptors.html) or Simple injector with dynamic proxy. Both have a really good documentation. Simple injector doesn't have an out of the box solution for interception because of their design rules but you can add an extension for it (http://simpleinjector.readthedocs.io/en/latest/aop.html).

以下是官方 SI 文档中的基本 AOP 场景:(http://simpleinjector.readthedocs.io/en/latest/InterceptionExtensions.html) :

Here is a basic AOP scenario from the official SI documentation:(http://simpleinjector.readthedocs.io/en/latest/InterceptionExtensions.html) :

//Add registration to the composition root
container.InterceptWith<MonitoringInterceptor>(serviceType => serviceType.Name.EndsWith("Repository"));`

// Here is an example of an interceptor implementation.
// NOTE: Interceptors must implement the IInterceptor interface:
private class MonitoringInterceptor : IInterceptor {
    private readonly ILogger logger;

  public MonitoringInterceptor(ILogger logger) {
        this.logger = logger;
    }

    public void Intercept(IInvocation invocation) {
        var watch = Stopwatch.StartNew();

        // Calls the decorated instance.
        invocation.Proceed();

        var decoratedType = invocation.InvocationTarget.GetType();

        this.logger.Log(string.Format("{0} executed in {1} ms.",
            decoratedType.Name, watch.ElapsedMilliseconds));
    }
}

这篇关于在 .NET Core 2.1 中使用 AOP 进行日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆