当前位置: 首页 > news >正文

Controller 自动化日志输出

Starter库

1.定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TraceLog {/*** 日志类型** @return*/String type() default "";
}

2.定义捕获日志接口方法

public interface ITraceLogProcess {void afterThrowing(JoinPoint pjp, Throwable ex, Long beforeTime);void afterReturning(JoinPoint pjp, Object result, Long beforeTime);void before(JoinPoint pjp);
}

3.定义捕获日志方法实现

@Slf4j
public class TraceLogProcess implements ITraceLogProcess {private static String UNKNOWN_IP = "unknown";private static String X_FORWARDED_FOR = "x-forwarded-for";@Overridepublic void afterThrowing(JoinPoint pjp, Throwable ex, Long beforeTime) {MethodSignature signature = (MethodSignature) pjp.getSignature();Method method = signature.getMethod();TraceLog traceLog = method.getAnnotation(TraceLog.class);Integer errorCode = ResultCode.UNKNOWN_CODE.getCode();String errorMsg = ResultCode.UNKNOWN_CODE.getDesc();if (ex instanceof ApiException) {errorCode = ((ApiException) ex).getResultCode();errorMsg = ex.getMessage();}HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();log.info("[Tracelog failed] Call interface[{}] from IP[{}] return error," +"URL:[{}], method name:[{}]," +"method type:[{}], expend time(ms):[{}]," +"input parameter:[{}]," +"error code:[{}], error message:[{}]",traceLog != null ? traceLog.type() : "", getIpAddr(request),request.getRequestURL().toString(), signature.getName(),request.getMethod(), System.currentTimeMillis() - beforeTime,pjp.getArgs(), errorCode, errorMsg);}@Overridepublic void afterReturning(JoinPoint pjp, Object result, Long beforeTime) {MethodSignature signature = (MethodSignature) pjp.getSignature();Method method = signature.getMethod();TraceLog traceLog = method.getAnnotation(TraceLog.class);HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();log.info("[Tracelog success]Call interface[{}] from IP[{}]," +"URL:[{}], method name:[{}]," +"method type:[{}], expend time(ms):[{}]," +"input parameter:[{}]," +"result:[{}]",traceLog != null ? traceLog.type() : "", getIpAddr(request),request.getRequestURL().toString(), signature.getName(),request.getMethod(), System.currentTimeMillis() - beforeTime,pjp.getArgs(), JSONObject.toJSONString(result));}@Overridepublic void before(JoinPoint pjp) {MethodSignature signature = (MethodSignature) pjp.getSignature();Method method = signature.getMethod();TraceLog traceLog = method.getAnnotation(TraceLog.class);HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();log.info("[Tracelog begin]Call interface[{}] from IP[{}]," +"URL:[{}], method name:[{}]," +"method type:[{}], input parameter:[{}]",traceLog != null ? traceLog.type() : "", getIpAddr(request),request.getRequestURL().toString(), signature.getName(),request.getMethod(), pjp.getArgs());}private String getIpAddr(HttpServletRequest request) {//获取代理服务器IP地址String proxyIp = request.getHeader(X_FORWARDED_FOR);//如果存在代理服务器IP地址,则从中提取客户端真实IP地址if (proxyIp != null && proxyIp.length() != 0) {String[] ips = proxyIp.split(",");for (String ip : ips) {if (!UNKNOWN_IP.equalsIgnoreCase(ip)) {return ip.trim();}}}//如果不存在代理服务器IP地址,则直接获取远程IP地址return request.getRemoteAddr();}
}

4.定义日志捕获切面

@Slf4j
@Aspect
public class TraceLogAspect {@Resource(name = "traceLogProcess")ITraceLogProcess traceLogProcess;private Long beforeTime;@AfterThrowing(throwing = "ex", value = "@annotation(uih.st.core.traceLog.TraceLog)")public void afterThrowing(JoinPoint pjp, Throwable ex) {traceLogProcess.afterThrowing(pjp, ex, beforeTime);}@AfterReturning(returning = "result", value = "@annotation(uih.st.core.traceLog.TraceLog)")public void afterReturning(JoinPoint pjp, Object result) {traceLogProcess.afterReturning(pjp, result, beforeTime);}@Before(value = "@annotation(uih.st.core.traceLog.TraceLog)")public void before(JoinPoint pjp) {this.beforeTime = System.currentTimeMillis();traceLogProcess.before(pjp);}
}

5.通过AutoConfiguration实现注入

@Configuration
@ConditionalOnWebApplication
public class TraceLogAutoConfiguration {@Bean(name = "traceLogProcess")@ConditionalOnMissingBean(name = "traceLogProcess")public ITraceLogProcess traceLogProcess() {return new TraceLogProcess();}@Beanpublic TraceLogAspect traceLogAspect() {return new TraceLogAspect();}
}

6.starter文件spring.factories新增类

org.springframework.boot.autoconfigure.EnableAutoConfiguration=core.TraceLogAutoConfiguration

应用使用

将上述实现的starter通过依赖引用后:

@TraceLog(type = "aaaaaa")
@PostMapping("/test")
public Result<Boolean> test() {return Result.success();
}
http://www.lryc.cn/news/371776.html

相关文章:

  • css3中有哪些新属性(特性)?
  • SAP ABAP 之面向对象OO
  • 在VSCode中使用Vim
  • 鸿蒙低代码开发的局限性
  • Codeforces Round 952 (Div. 4) c++题解(A-H1)
  • 人工智能将成为数学家的“副驾驶”
  • 自适应巡航控制技术规范(简化版)
  • 【AI】文心一言的使用分享
  • Java学习-MyBatis学习(四)
  • 多源最短路径算法 -- 弗洛伊德(Floyd)算法
  • 同三维T80005EH4 H.265 4路高清HDMI编码器
  • 焦化行业排放平台简介
  • 『原型资源』Axure自带图标库不够用,第三方经典图标库来袭
  • 修改版的VectorDBBench更好用
  • 六西格玛培训都培训哪些内容 ?
  • K8S环境部署Prometheus
  • 在linux系统上挂载新硬盘
  • 1004.最大连续1的个数
  • 【机器学习300问】116、什么是序列模型?序列模型能干什么?
  • kafka 快速上手
  • Python记忆组合透明度语言模型
  • 如何保证数据库和缓存的一致性
  • Java基础 - 多线程
  • 云顶之弈-测试报告
  • TCP/IP协议分析实验:通过一次下载任务抓包分析
  • Python项目开发实战:企业QQ小程序(案例教程)
  • list模拟与实现(附源码)
  • Java应用中文件上传安全性分析与安全实践
  • noVNC 小记
  • 设置systemctl start kibana启动kibana