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

2024-09-03 14:52

本文主要是介绍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);}}

使用

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

这篇关于AOP和注解的配合使用(封装通用日志处理类)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1133276

相关文章

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

mapstruct中的@Mapper注解的基本用法

《mapstruct中的@Mapper注解的基本用法》在MapStruct中,@Mapper注解是核心注解之一,用于标记一个接口或抽象类为MapStruct的映射器(Mapper),本文给大家介绍ma... 目录1. 基本用法2. 常用属性3. 高级用法4. 注意事项5. 总结6. 编译异常处理在MapSt

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.