【问题标题】:Cross cutting concern logging横切关注日志
【发布时间】:2015-09-27 01:29:38
【问题描述】:

我想记录有关正在执行的方法的某些信息,我认为 AOP 没问题,敲了一个演示,但我确实需要记录每个方法的具体信息,将其视为与调用相关的附加信息。

现在我考虑的选项只是在每个方法中记录它,但我认为它会污染代码,最后的手段,也许

或者我创建一个类,将方法映射到需要记录的信息,并使用 AOP 记录这些信息。

你们觉得呢?

【问题讨论】:

  • 你有一个具体的例子说明每种方法会有什么不同吗?

标签: design-patterns cross-cutting-concerns


【解决方案1】:

您还可以考虑使用环境上下文模式来实现横切关注点。有一个不错的博客:Ambient Context

【讨论】:

    【解决方案2】:

    另一种方法可能是Decorator pattern/Interceptor pattern,但会增加编码工作量:

    interface IComponent
    {
        int Foo(int input);
    }
    
    class Component : IComponent
    {
        public int Foo(int input)
        {
            return input * 2;
        }
    }
    
    class LoggingComponent: IComponent
    {
        private readonly IComponent target;
    
        public LoggingComponent(IComponent target)
        {
            this.target = target;
        }
    
        public int Foo(int input)
        {
            // ToDo: Add logging before method call
    
            int returnValue = this.target.Foo(input);
    
            // ToDo: Add logging after method call
    
            return returnValue;
        }
    }
    

    使用这种方法需要为所有要记录方法调用和输入/返回值的目标实现大量日志记录类。此外,您无法记录装饰器/拦截器转发到的目标方法内部发生的情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 2021-10-31
      • 2011-08-01
      • 1970-01-01
      相关资源
      最近更新 更多