日志切面的设计(不同通知的日志用处)

阅读更多

日志切面;

日志的打印用切面拦截,切面中执行切点之前打印参数,执行切点之后打印返回的结果

 

方式一:用环绕通知把方法的请求,返回一起打印

 @Pointcut("execution(* com.houbank.incoming.web.controller..*(..)) and  @within(org.springframework.web.bind.annotation.Controller)")

    private void anyAcesssAndResponseMethdod() {

    }

 

 @Around("anyAcesssAndResponseMethdod()")中打印请求参数,返回结果都在这一个环绕通知中

 public Object doAround(ProceedingJoinPoint p) throws Throwable {

StringBuffer sb = new StringBuffer("类名:");

log.info(assemble(p,"doBefore"));

 

String targetName = p.getTarget().getClass().getName();

String methodName = p.getSignature().getName();

sb.append(targetName);

sb.append(".");

sb.append(methodName);

sb.append("()");

sb.append("--参数:");

Object result = null;

result = p.proceed();

try {

sb.append("serviceImpl_Result---"+ JSON.toJSONString(result));

sb.append("---serviceImpl_Result---END");

log.info(sb.toString());

} catch (Throwable e) {

log.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> CommonLog.doAround()" + "-参数:" + sb + e.getMessage(),e);

}

 

log.info(assemble(p,"doAfter"));

return result;

}

 

 

 

方式二:用前置通知,后置通知分别打印请求,返回数

 

@Pointcut("execution(* com.houbank.incoming.service.impl.*.*(..))")  

    public void methodPointcut() {}

 

@Before("methodPointcut()")

    public void before(JoinPoint joinPoint) {

        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

        //查询不记录日志

        if(method.getName().startsWith("select") || method.getName().startsWith("get") || method.getName().startsWith("query")) {

        return;

        }

        StringBuilder sb = new StringBuilder();

        sb.append(method.getDeclaringClass().getSimpleName()).append(".").append(method.getName()).append(" req:");

        for(int i = 0; i < joinPoint.getArgs().length; i++) {

        sb.append(joinPoint.getArgs()[i]);

        }

        log.info(sb.toString());

    }

 

@AfterReturning(returning="rvt", pointcut="methodPointcut()")

    public void after(JoinPoint joinPoint, Object rvt) {

        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

        //查询不记录日志

        if(method.getName().startsWith("select") || method.getName().startsWith("get") || method.getName().startsWith("query")) {

        return;

        }

        log.info(method.getDeclaringClass().getSimpleName() + "."+ method.getName() + " resp:" + rvt);

    }

 

 

然后异常通知打印异常时的日志

 

 

@AfterThrowing(value = "execution(* com.houbank.newapi.web.api..*.*(..))", throwing = "e")

public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {

String errorMsg = assemble(joinPoint, "throwing") + e.getMessage();

log.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> CommonLog.assemble()" + "-参数:" + errorMsg);

}

 

 

  • 新建文件夹.zip (4.6 KB)
  • 下载次数: 0

你可能感兴趣的:(架构)