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

相关文章

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat

C++中std::distance使用方法示例

《C++中std::distance使用方法示例》std::distance是C++标准库中的一个函数,用于计算两个迭代器之间的距离,本文主要介绍了C++中std::distance使用方法示例,具... 目录语法使用方式解释示例输出:其他说明:总结std::distance&n编程bsp;是 C++ 标准

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain