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

AOP和注解的配合使用(封装通用日志处理类)

自定义注解

@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {String value() default "";
}

定义切面

@Aspect
@Component
@Slf4j
public class LogAop {// 定义识别自定义注解的切点@Pointcut("@annotation(com.jxy.MyLog)")public void logger(){}/**** @param point* @return*/@Around("logger()")public Object around(ProceedingJoinPoint point) {Object obj = null;String ip_port = "";String uri = "";String value="";HttpServletResponse response = null;ControllerLogMapper bip2NCLogMapper = null;bip2NCLogMapper = AppContext.getBean(ControllerLogMapper.class);Signature methodName = point.getSignature();String name = point.getSignature().getName();log.error(methodName + "....running");//Long start = System.currentTimeMillis();Object[] argArray = point.getArgs();if (argArray != null && argArray.length > 0) {for (Object object : argArray) {if (object instanceof HttpServletResponse) {response = (HttpServletResponse) object;}}}// 目标方法执行try {Object res = point.proceed(point.getArgs());obj = res ;} catch (Throwable throwable) {obj = "【" + name + "方法异常,异常信息:" + throwable + "】";log.error("【环绕异常通知】【" + name + "方法异常,异常信息:" + throwable + "】");throw new GlobalException(throwable.getMessage());} finally {try {if (response != null) {PrintWriter writerToBeRead = response.getWriter();CoyoteWriter cw = (CoyoteWriter) writerToBeRead.append("");Class<?> clazz = cw.getClass();Field declaredField = clazz.getDeclaredField("ob");declaredField.setAccessible(true);OutputBuffer ob = (OutputBuffer) declaredField.get(cw);Class<?> classOutputBuffer = ob.getClass();//获取IP和端口 startClass<?> responseClass = response.getClass();Field requestField = responseClass.getDeclaredField("request");requestField.setAccessible(true);HttpServletRequest request = (HttpServletRequest) requestField.get(response);String ip = request.getRemoteAddr();//获取请求地址uri = request.getRequestURI();Field coyoteResponseField = classOutputBuffer.getDeclaredField("coyoteResponse");coyoteResponseField.setAccessible(true);Response coyoteResponse = (Response) coyoteResponseField.get(ob);Class<?> coyoteResponseClass = coyoteResponse.getClass();Field reqField = coyoteResponseClass.getDeclaredField("req");reqField.setAccessible(true);Request request1 = (Request) reqField.get(coyoteResponse);int port = request1.getServerPort();ip_port = ip + ":" + port;//获取IP和端口 endField fieldOutputChunk = classOutputBuffer.getDeclaredField("cb");fieldOutputChunk.setAccessible(true);obj = fieldOutputChunk.get(ob) == null ? "" : fieldOutputChunk.get(ob).toString();}MethodSignature signature = (MethodSignature) point.getSignature();MyLog declaredAnnotation = signature.getMethod().getDeclaredAnnotation(MyLog.class);value = declaredAnnotation.value();log.error("==注解@MyLog的value=="+ value);//记录到日志表String loginUser = AppContext.getCurrentUser() == null ? "第三方调用" : AppContext.getCurrentUser().getId().toString();String YTenantId = com.yonyou.eforship.common.utils.yms.AppContextUtil.getCurrentOrDefaultTenantId() == null ? "" : com.yonyou.eforship.common.utils.yms.AppContextUtil.getCurrentOrDefaultTenantId().toString();bip2NCLogMapper.add(String.valueOf(IdManager.getInstance().nextId()), loginUser, ArrayUtils.toString(argArray, ","), obj == null?"":obj.toString(), methodName.toString(), YTenantId, ip_port,uri,value);} catch (Exception e) {log.error("ControllerLog接口日志创建异常:" + e.getMessage());}log.error("【环绕后置通知】【" + name + "方法结束】");}//Long end = System.currentTimeMillis();//log.info(methodName + "....stop" + "\t耗时:" + (end - start));return obj;}public String getResponseContent(HttpServletResponse response) throws IOException, NoSuchFieldException, IllegalAccessException {String responseContent = null;CoyoteOutputStream outputStream = (CoyoteOutputStream) response.getOutputStream();Class<CoyoteOutputStream> coyoteOutputStreamClass = CoyoteOutputStream.class;Field obField = coyoteOutputStreamClass.getDeclaredField("ob");if (obField.getType().toString().endsWith("OutputBuffer")) {obField.setAccessible(true);org.apache.catalina.connector.OutputBuffer outputBuffer = (org.apache.catalina.connector.OutputBuffer) obField.get(outputStream);Class<org.apache.catalina.connector.OutputBuffer> opb = org.apache.catalina.connector.OutputBuffer.class;Field outputChunkField = opb.getDeclaredField("outputChunk");outputChunkField.setAccessible(true);if (outputChunkField.getType().toString().endsWith("ByteChunk")) {ByteChunk bc = (ByteChunk) outputChunkField.get(outputBuffer);Integer length = bc.getLength();if (length == 0) return null;responseContent = new String(bc.getBytes(), "UTF-8");Integer responseLength = StringUtils.isBlank(responseContent) ? 0 : responseContent.length();if (responseLength < length) {responseContent = responseContent.substring(0, responseLength);} else {responseContent = responseContent.substring(0, length);}}}return responseContent;}/*** 如果程序出现了异常,则需要拦截,打印异常信息* @param joinPoint* @param throwable*/@AfterThrowing(pointcut = "logger()",throwing = "throwable")public void afterThrow(JoinPoint joinPoint, Throwable throwable) {Class<?> targetClass = joinPoint.getTarget().getClass();String methodName = joinPoint.getSignature().getName();Class<?> throwClass = throwable.getClass();String msg = throwable.getMessage();log.error("目标对象类型:" + targetClass);log.error("目标方法:" + methodName);log.error("异常类型:" + throwClass);log.error("异常信息:" + msg);}}

使用

该自定义注解作用于方法上,如果需要日志处理,直接使用注解即可。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 2 html5 浏览器已经支持的新API
  • 腾讯云技术深度解析:AI代码助手与微服务架构的实践应用
  • 服务器数据恢复—如何应对双循环RAID5阵列的数据丢失问题?
  • 【初出江湖】分布式之什么是分布式存储?
  • P-Tuning v2:一种普遍有效的提示调整方法
  • 三分钟搭建线上RAG应用,实现定制化的知识库问答
  • 解锁企业微信营销新纪元:智驭未来,让每一次触达都精准高效!
  • Tensorflow实现深度学习8:猫狗识别
  • Qt Dialog退出事件
  • AIGC时代从新手到高手:B端竞品分析实战案例与技巧分享
  • 华为Huawei路由器交换机SSH配置
  • 设计模式-结构型模式-组合模式
  • 学习WebGl基础知识(二)
  • Docker原理及实例
  • 使用docker部署project-exam-system(项目)
  • 【159天】尚学堂高琪Java300集视频精华笔记(128)
  • Android单元测试 - 几个重要问题
  • canvas实际项目操作,包含:线条,圆形,扇形,图片绘制,图片圆角遮罩,矩形,弧形文字...
  • css选择器
  • Java新版本的开发已正式进入轨道,版本号18.3
  • js写一个简单的选项卡
  • Object.assign方法不能实现深复制
  • Protobuf3语言指南
  • Web标准制定过程
  • 规范化安全开发 KOA 手脚架
  • 技术攻略】php设计模式(一):简介及创建型模式
  • 模仿 Go Sort 排序接口实现的自定义排序
  • 如何编写一个可升级的智能合约
  • 智能网联汽车信息安全
  • 走向全栈之MongoDB的使用
  • zabbix3.2监控linux磁盘IO
  • ​​​​​​​Installing ROS on the Raspberry Pi
  • ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException
  • ######## golang各章节终篇索引 ########
  • #07【面试问题整理】嵌入式软件工程师
  • $(function(){})与(function($){....})(jQuery)的区别
  • $.ajax()参数及用法
  • %check_box% in rails :coditions={:has_many , :through}
  • (7) cmake 编译C++程序(二)
  • (floyd+补集) poj 3275
  • (黑马点评)二、短信登录功能实现
  • (每日持续更新)信息系统项目管理(第四版)(高级项目管理)考试重点整理第3章 信息系统治理(一)
  • (强烈推荐)移动端音视频从零到上手(上)
  • (贪心) LeetCode 45. 跳跃游戏 II
  • (心得)获取一个数二进制序列中所有的偶数位和奇数位, 分别输出二进制序列。
  • (转)C语言家族扩展收藏 (转)C语言家族扩展
  • .axf 转化 .bin文件 的方法
  • .md即markdown文件的基本常用编写语法
  • .Net 8.0 新的变化
  • .NET CLR基本术语
  • .net FrameWork简介,数组,枚举
  • .NET 使用 ILMerge 合并多个程序集,避免引入额外的依赖
  • .net 使用ajax控件后如何调用前端脚本
  • .NET/C# 使用 SpanT 为字符串处理提升性能
  • .NET+WPF 桌面快速启动工具 GeekDesk