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

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式