Spring – slf4J:如何自动记录错误和exception?

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

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

问候,

exception方面可能如下所示:

@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; } } } 

springconf:

        

编辑:

如果你想让记录器代表被包装的bean登录,你当然可以这样做:

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

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

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

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

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

 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: * 
    *
  • they are public
  • *
  • the are located in a class of name *SericeImpl within (implement an interface) * {@link test.service} package
  • *
  • they are located within a class with an {@link Service} annotation
  • *
*/ 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编写的,但您可以轻松地对其进行调整。