代码之家  ›  专栏  ›  技术社区  ›  Suminda Sirinath S. Dharmasena

使用eclipseaspectj注入一个日志记录器来记录执行代码的上下文/元数据?

  •  0
  • Suminda Sirinath S. Dharmasena  · 技术社区  · 4 年前

    我试图定义一个方面来注入一个记录器。

    我想创造一些东西,比如:

    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    
    public aspect LogInjector {
    
        private pointcut executionJoinPoints(): !within(LogInjector) && execution (* *.*(..));
    
        before(): executionJoinPoints(){
            // Get class name of the executed code
            clazz = ...
            final Logger logger = LogManager.getLogger(clazz);
    
            // Get method name of the executed code
            method = ...
    
            // Get params name, type and values triplet or values at least if the previous is not possible, of the executed code
            params = ...
    
            // Get call stack of the executed code
            stack = ...
    
            logger.trace("{}.{}({}) - {}", clazz.name(), method.name(), params, stack);
        }
    
        after(): executionJoinPoints(){
            // Get class name of the executed code
            clazz = ...
            final Logger logger = LogManager.getLogger(clazz);
    
            // Get method name of the executed code
            method = ...
    
            // Get return value or exception of the executed code
            result = ...
    
            logger.trace("{}.{} = {}", clazz.name(), method.name(), result);
        }
    }
    
    

    为此,我要检索执行元数据/上下文数据:

    • 返回值

    如何获取此元数据/上下文数据?

    0 回复  |  直到 4 年前
        1
  •  1
  •   kriegaex    4 年前

    为了保持您的方面的效率,我建议如下:

    • 将切入点限制在真正希望调试的目标包和类上。不要记录/追踪整个世界。您还可以使用带有抽象切入点的抽象基本方面,并使用具体切入点将该方面扩展为具体的子方面。如果使用加载时编织,甚至可以通过XML配置提供后者。
    • 使用 around() before() / after() 一对。然后只需计算一次某些记录的值,并在通过完成原始方法调用之前和之后使用它们 proceed()
    • thisJoinPoint 而不是在默认情况下拼凑其中包含的位。这已经为您提供了joinpoint的类型、方法签名(包括参数类型和返回值)。
    • 不要记录参数名,这些信息不会增加实际值。此外,参数名要经过重构,并且只有在使用调试信息编译代码时才会出现。保持简单,只记录参数值。
    • 大约() 上述建议请随函附上 召唤 try-catch-finally SoftException 或者一个简单的 RuntimeException 再把它们扔出去。任何适合你的情况。
    • 继续() 建议。也可以返回其他内容(但必须有正确的返回类型)或完全跳过 如果出于任何原因希望跳过目标方法执行。

    我刚才说的所有内容都写在AspectJ手册或任何其他AspectJ教程中。下一次你可能想在问像这样的一般性问题之前读一些。