使用c#方法局部变量进行日志记录的AOP工具

本文关键字:记录 AOP 工具 日志 方法 局部变量 使用 | 更新日期: 2023-09-27 18:06:48

Unity Interception可以用来拦截方法,它可以捕获被拦截方法的参数值。

我想要的是记录截获方法中局部变量的值。例如

public void CopyBlogPost(int id){
  var oldblogPost = GetBlogPost(id);
  //log details about old blog post, including name, date, id etc.
  //copy post
 //log details about new blog post, including name, date, id etc.
}

是否有工具可以用于此场景?

正如@Aron建议的那样,Mono。Cecil可能会提供这个功能

使用c#方法局部变量进行日志记录的AOP工具

你可以这样定义一个装饰器:

public class LoggingCalculatorDecorator : ICalculator
{
    private readonly ICalculator decoratee;
    private readonly ILogger logger;
    public LoggingCalculatorDecorator(
        ICalculator decoratee,
        ILogger logger)
    {
        this.decoratee = decoratee;
        this.logger = logger;
    }
    public void Add(int i, int j)
    {
        var logging = "adding "+i+" "+j;
        //Log logging variable, or any local variables
        // call decoratee
        this.decoratee.Add(i, j);
    }
}
通过这种方式,您可以将此行为添加到现有类中,而无需对其进行更改。如果您发现自己在整个系统中添加了许多日志装饰器(并且违反了DRY原则),那么您可能错过了系统中的公共抽象。看看这个和这篇文章。它们可能会给您一些提示,告诉您如何设计系统,而不需要退回到拦截和代码编织,而是解决核心问题:应用程序的设计。