Spring Cloud Sleuth 和 Zipkin 进行分布式跟踪使用小结
295
2022-08-18
springboot利用@Aspect实现日志工具类的详细代码
目录一、导包二、在启动类上进行注解自动扫描三、工具类四、结果
一、导包
二、在启动类上进行注解自动扫描
@SpringBootApplication
@EnableCaching
@EnableAsync
@ComponentScan({"com.workorder.*"})
public class WorkOrderApplication {
public static void main(String[] args) {
SpringApplication.run(WorkOrderApplication.class, args);
}
}
三、工具类
@Aspect
@Component
@Slf4j
public class LogAspect {
@Autowired
private Environment env;
@Pointcut("execution(public * com.workorder..controller..*.*(..))")
public void logPointCut()
{}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
log.info("=========================================");
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//保存日志
saveSysLog(point, time);
return result;
}
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String logStr="";
if (isEnvironment("dev")){
String requestUrl = request.getRequestURL().toString() + "?";
//获取所有参数方法
Enumeration
while(enu.hasMoreElements()){
String paraName = enu.nextElement();
requestUrl+=paraName + "=" + request.getParameter(paraName) + "&";
}
logStr+="\r\n请求地址:"+ requestUrl.substring(0,requestUrl.length()-1);
}
//请求的参数
Object[] args = joinPoint.getArgs();
String params = jsONUtil.toJsonStr(args);
logStr+="\r\n请求方式:"+ request.getMethod();
logStr+="\r\n请求方法Token:"+ request.getHeader("token");
logStr+="\r\n请求参数:"+http:// params;
logStr+="\r\nIP:"+ request.getRemoteAddr();
logStr+="\r\n响应时间:"+ time+" ms";
log.info(logStr);
/**
* 判断当前是什么环境
* @param str
* @return
*/
private boolean isEnvironment(String str) {
boolean flag = false;
String[] arr = env.getActiveProfiles();
List
if (list.contains(str)) {
flag = tTlpCLPIxrue;
}
return flag;
}
}
四、结果
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~