当然使用aop来做咯。

代码如下。

import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.AfterThrowing;

import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Pointcut;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect

@Component

public class LoggingAspect {

private final Logger log = LoggerFactory.getLogger(this.getClass());

@Pointcut("within(@org.springframework.stereotype.Repository *)" +

" || within(@org.springframework.stereotype.Service *)" +

" || within(@org.springframework.web.bind.annotation.RestController *)")

public void springBeanPointcut() {

}

@Pointcut("within(com.fanxian.logic.*.repository..*)"+

" || within(com.fanxian.logic.*.service..*)"+

" || within(com.fanxian.logic.*.controller..*)")

public void applicationPackagePointcut() {

}

@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")

public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {

log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),

joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);

}

@Around("applicationPackagePointcut() && springBeanPointcut()")

public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {

if (log.isDebugEnabled()) {

log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),

joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));

}

try {

Object result = joinPoint.proceed();

if (log.isDebugEnabled()) {

log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),

joinPoint.getSignature().getName(), result);

}

return result;

} catch (IllegalArgumentException e) {

log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),

joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

throw e;

}

}

}

springBeanPointcut方法配置了spring注解的切入点,applicationPackagePointcut则为你想要拦截方法的切入点。

logAfterThrowing为拦截捕获到的异常,logAround环绕方法获取到拦截的方法打印方法名,输入的参数等等,再往下的Object result = joinPoint.proceed();为调用目标方法,最后打印了返回值。

你需要的只是获取输入的参数,所以joinPoint.getArgs()就是你需要的方法。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐