日志切面类

package cn.yto.stl.freight.web.api.common.aspect;

import cn.yto.base.exception.IException;
import cn.yto.stl.freight.web.api.common.domain.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;

@SuppressWarnings("ALL")
@Component
@Aspect
@Slf4j
public class ControllerAop {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

@Pointcut("@annotation(cn.yto.stl.freight.web.api.common.aspect.Log)")
public void executeService() {
}

/**
* 环绕通知, 围绕着方法执行
*
* @param joinPoint
* @return
* @throws Throwable
*/
@Around("executeService()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("收到请求:Around ====================================================");

long start = System.currentTimeMillis();

try {

//获取IP
// String ip = IpUtil.getIpAddr(request);

Object[] args = joinPoint.getArgs();// 参数
int argsSize = args.length;
String argsTypes = "";

String typeStr = joinPoint.getSignature().getDeclaringType().toString().split(" ")[0];
String returnType = joinPoint.getSignature().toString().split(" ")[0];

// User userInfo = RequestContext.getUserInfo();

// 记录下请求内容
// log.info("IP 地址 : " + ip);
log.info("请求时间 : " + sdf.format(start));

// String uid = userInfo != null ? userInfo.getUId().toString() : null;
// if (StringUtils.isBlank(uid)) {
// uid = "未登录";
// }
//
// log.info("当前用户UID:" + uid);

log.info("执行方法 : " + joinPoint.getSignature());
log.info("执行参数 : " + Arrays.toString(joinPoint.getArgs()));

//执行方法
Object result = joinPoint.proceed();

// 处理完请求,返回内容
if ("DataResult".equals(returnType)) {
DataResult apiResult = (DataResult) result;
if (apiResult.getStatus() != null) {
log.info("返回状态码:" + apiResult.getStatus());
} else {
log.info("返回状态码为空");
}

if (apiResult.getData() != null) {
log.info("返回数据 : " + apiResult.getData().toString());
} else {
log.info("返回数据为空");
}
}

long end = System.currentTimeMillis();
Long total = end - start;
log.info("aspect耗时 : " + total + " ms!");
// log.info("执行完成 :==========================================================================================");
return result;

} catch (Throwable e) {
if (e instanceof IException) {
throw e;
}

// 获取类的包名 如果包含yto则throw
Class targetClass = e.getClass();
String packageName = targetClass.getPackage().toString();
log.debug("aop捕捉异常packageName:" + packageName);
if (packageName.contains("yto")) {
throw e;
}

log.error("aop捕捉异常", e);
return DataResult.fail();
}
}
}
posted @ 2022-08-24 14:47  却道。此心安处是吾乡  阅读(21)  评论(0编辑  收藏  举报