Spring - slf4J:如何自动记录错误和异常?

时间:2011-03-15 09:23:58

标签: java hibernate spring aspectj slf4j

我们正在使用Spring和slf4j以及hibernate,我正试图找出一种自动记录异常和错误的方法(即不在每个类中启动调试器的实例),以便它可以捕获任何错误或异常抛出并在日志中获取类和方法名称,

我读了一篇关于使用方面的简短说明&这个拦截器,你能否为我提供一些实现这个的详细方法,

此致

2 个答案:

答案 0 :(得分:10)

异常方面可能如下所示:

@Aspect
public class ExceptionAspect {

  private static final Logger log = LoggerFactory.getLogger(ExceptionAspect.class);

  public Object handle(ProceedingJoinPoint pjp) throws Throwable {
     try {
       return pjp.proceed();
     } catch (Throwable t) {
       // so something with t: log, wrap, return default, ...
       log.warn("invocation of " + pjp.getSignature().toLongString() + " failed", t);
       // I hate logging and re-raising, but let's do it for the sake of this example
       throw t;
     }
  }
}

spring conf:

<!-- log exceptions for any method call to any object in a package called 'svc' -->
<bean class="org.example.aspects.ExceptionAspect" name="exceptionAspect" />
<aop:config>
  <aop:aspect ref="exceptionAspect">
    <aop:around method="handle" pointcut="execution(* org.example..svc..*.*(..))" />
  </aop:aspect>
</aop:config>

编辑:

如果您希望记录器代表包装的bean进行登录,您当然可以这样做:

LoggerFactory.getLogger(pjp.getTarget().getClass()).warn("damn!");

或者如果您优先使用此方法的声明类而不是实际(可能代理/自动生成的类型):

LoggerFactory.getLogger(pjp.getSignature().getDeclaringType()).warn("damn!");

老实说,我无法估计每次调用LoggerFactory.getLogger(..)的性能影响。我认为这不应该太糟糕,因为异常是特殊的(即罕见的)。

答案 1 :(得分:0)

使用纯粹的Aspect J(也可以使用它而不是Spring托管bean)。 此示例记录服务方法“返回”的所有异常。但是你也可以改变它与其他方法匹配的切入点。

package test.infrastructure.exception;

import java.util.Arrays;

import org.apache.log4j.*;
import org.aspectj.lang.Signature;
import org.springframework.stereotype.Service;

/** Exception logger*/
public aspect AspectJExceptionLoggerAspect {

    /** The name of the used logger. */
    public final static String LOGGER_NAME = "test.infrastructure.exception.EXCEPTION_LOGGER";

    /** Logger used to log messages. */
    private static final Logger LOGGER = Logger.getLogger(LOGGER_NAME);

    AspectJExceptionLoggerAspect() {
    }

    /**
     * Pointcut for all service methods.
     * 
     * Service methods are determined by two constraints:
     * <ul>
     *   <li>they are public</li>
     *   <li>the are located in a class of name *SericeImpl within (implement an interface)
     *   {@link test.service} package</li>
     *   <li>they are located within a class with an {@link Service} annotation</li>
     * </ul>
     */
    pointcut serviceFunction()
        : (execution(public * test.Service.*.*ServiceImpl.*(..)))  
        && (within(@Service *));

    /** Log exceptions thrown from service functions. */
    after() throwing(Throwable ex) : serviceFunction() {
        Signature sig = thisJoinPointStaticPart.getSignature();
        Object[] args = thisJoinPoint.getArgs();

        String location = sig.getDeclaringTypeName() + '.' + sig.getName() + ", args=" + Arrays.toString(args);
        LOGGER.warn("exception within " + location, ex);        
    }
}

它是为JUnit编写的,但你可以轻松地适应它。