我们将 Spring 与 slf4j 和休眠一起使用,我正在尝试找出一种自动记录异常和错误的方法(即,无需在每个类中启动调试器的实例),以便它可以捕获任何错误或抛出的异常,并且在日志中获取类和方法名,
我读了一篇关于为此使用方面和拦截器的简短说明,所以您能否提供一些详细的方法来实现这一点,
问候,
异常方面可能如下所示:
@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;
}
}
}
春季会议:
<!-- 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(..) 对性能的影响。我认为它不应该太糟糕,因为无论如何例外都是例外的(即罕见的)。
使用纯 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 编写的,但您可以轻松适应它。