【问题标题】:Add logger with Spring使用 Spring 添加记录器
【发布时间】:2014-04-07 14:08:30
【问题描述】:

有没有办法用 Spring 添加一个记录器实例? 有没有办法在我的自定义代码中跟踪每个方法调用?

我通常这样做:

package my.java.code;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class A {
  // How to add this line with Spring ?
  private static final Logger logger = LoggerFactory.getLogger(A.class);
  public void A() {
    // How to add this line with Spring ?
    logger.trace("");
    // Do something...
  }
  public void A(Object o) {
    // How to add this line with Spring ?
    logger.trace("{}", o);
    // Do something...
  }
  public void method1() {
    // How to add this line with Spring ?
    logger.trace("");
    // Do something...
  }
  public void method2(Object o) {
    // How to add this line with Spring ?
    logger.trace("{}", o);
    // Do something...
  }
}

有没有办法用 Spring 来简化这个?

目标是:

  • 避免重复代码

【问题讨论】:

标签: java spring logging trace


【解决方案1】:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

  <bean id="customizableTraceInterceptor"
    class="org.springframework.aop.interceptor.CustomizableTraceInterceptor">
    <property name="enterMessage"
      value="Entering $[targetClassName].$[methodName]($[argumentTypes] $[arguments])" />
    <property name="exitMessage" value="Leaving $[methodName](): $[returnValue]" />
  </bean>

  <aop:config>
    <aop:advisor advice-ref="customizableTraceInterceptor"
      pointcut="execution(* fr.my.package.dao..*.*(..))" />
  </aop:config>

</beans>

这有助于我跟踪 fr.my.package.dao 包中所有类的所有方法的每次调用。

感谢@m-deinum

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多