在日常开发工作中,我们免不了要打印很多log。而大部分需要输出的log又是重复的(例如传入参数,返回值)。
因此,通过AOP方式来进行日志管理可以减少很多代码量,也更加优雅。

Springboot通过AOP方式(@Aspect)和Javassist优雅地进行日志输出管理。

主要使用技术:Aspect,Javassist

package com.xinyartech.erp.system.aop;

import java.lang.reflect.Modifier;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON;
import com.xinyartech.erp.core.util.Util; import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo; /**
* 通过spring aop实现service方法执行时间监控
*
* @author Lynch
*
*/
@Aspect
@Component
public class WebLogAop {
private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(WebLogAop.class); private static ThreadLocal<String> threadLocal = new ThreadLocal<String>(); //public static final String POINT = "execution (* com.xinyartech.erp.*.web.*.*(..))"; @Pointcut("(execution (* com.xinyartech.erp.*.web.*.*(..)))")
public void webLog(){ } /**
* 前置通知
* @param joinPoint 切点
* @throws Throwable 异常
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
String uuid = Util.getUUID();
threadLocal.set(uuid); String classType = joinPoint.getTarget().getClass().getName();
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
log.info(String.format("[%s] 类名:%s", uuid, clazzName));
String methodName = joinPoint.getSignature().getName();
log.info(String.format("[%s] 方法名:%s", uuid, methodName));
String[] paramNames = getFieldsName(this.getClass(), clazzName, methodName);
Object[] args = joinPoint.getArgs();
for(int k=0; k<args.length; k++){
log.info("[" + uuid + "] 参数名:" + paramNames[k] + ",参数值:" + JSON.toJSONString(args[k]));
}
} /**
* 后置通知
* 打印返回值日志
* @param ret 返回值
* @throws Throwable 异常
*/
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
String uuid = threadLocal.get();
String classType = joinPoint.getTarget().getClass().getName();
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
log.info(String.format("[%s] 类名:%s", uuid, clazzName));
String methodName = joinPoint.getSignature().getName();
log.info(String.format("[%s] 方法名:%s", uuid, methodName));
log.info(String.format("[%s] 返回值 : %s", uuid, JSON.toJSONString(ret)));
log.info("*****************************************");
} /**
* 得到方法参数的名称
* @param cls 类
* @param clazzName 类名
* @param methodName 方法名
* @return 参数名数组
* @throws NotFoundException 异常
*/
private static String[] getFieldsName(Class<?> cls, String clazzName, String methodName) throws NotFoundException {
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath); CtClass cc = pool.get(clazzName);
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramNames.length; i++){
paramNames[i] = attr.variableName(i + pos); //paramNames即参数名
}
return paramNames;
}
}

AOP统一日志打印处理的更多相关文章

  1. SpringBoot统一日志打印

    统一日志打印 @Slf4j @Aspect @Component public class ControllerLog { private static final ThreadLocal<Lo ...

  2. 【Java分享客栈】超简洁SpringBoot使用AOP统一日志管理-纯干货干到便秘

    前言 请问今天您便秘了吗?程序员坐久了真的会便秘哦,如果偶然点进了这篇小干货,就麻烦您喝杯水然后去趟厕所一边用左手托起对准嘘嘘,一边用右手滑动手机看完本篇吧. 实现 本篇AOP统一日志管理写法来源于国 ...

  3. 简单的aop实现日志打印(切入点表达式)

    Spring中可以使用注解或XML文件配置的方式实现AOP. 1.导入jar包 com.springsource.net.sf.cglib -2.2.0.jar com.springsource.or ...

  4. 基于XML配置的AOP实现日志打印

    Spring中可以使用注解或XML文件配置的方式实现AOP.1.导入jar包 com.springsource.net.sf.cglib -2.2.0.jar com.springsource.org ...

  5. SpringBoot | 第二十四章:日志管理之AOP统一日志

    前言 上一章节,介绍了目前开发中常见的log4j2及logback日志框架的整合知识.在很多时候,我们在开发一个系统时,不管出于何种考虑,比如是审计要求,或者防抵赖,还是保留操作痕迹的角度,一般都会有 ...

  6. Spring AOP统一日志 全量日志

    Spring AOP 切面@Around注解的具体使用 lichuangcsdn 2019-02-19 23:21:36 63936 收藏 61分类专栏: Spring 文章标签: Spring AO ...

  7. PHP框架(如:laravel、yii2、thinkPHP5)中统一异常处理及统一日志打印

    背景: 现在写接口服务应用有一个很通用的需求,想通过日志.或者监控的形式监测的接口的运行情况,比如耗时.请求参数.响应结果.和前端联调接口时或者排查线上问题时日志必不可少,特别是现场日志. 应用运行时 ...

  8. springboot aop + logback + 统一异常处理 打印日志

    1.src/resources路径下新建logback.xml 控制台彩色日志打印 info日志和异常日志分不同文件存储 每天自动生成日志 结合myibatis方便日志打印(debug模式) < ...

  9. Spring AOP实现统一日志输出

    目的: 统一日志输出格式 思路: 1.针对不同的调用场景定义不同的注解,目前想的是接口层和服务层. 2.我设想的接口层和服务层的区别在于: (1)接口层可以打印客户端IP,而服务层不需要 (2)接口层 ...

随机推荐

  1. 深浅拷贝_python

    一.浅拷贝 拷贝第一层的东西,如其他列表修改他们共同的第二层(或更深),他管不了,只能跟着变. 用处:很少用,用不同账号关联共享: import copyhusband= ['chen','123', ...

  2. 格式化输出_python

    一.直接使用 +a='chen'b='xiao'c='zan'print(a+b+c) 二.利用占位符 %%s:占位符:%d:整数:%x:十六进制:%f:浮点数(默认6位小数)特别注意浮点数: 指定长 ...

  3. JavaWeb项目忘记添加依赖

    有的时候我们建项目的时候忘记添加项目的依赖了,这里示范一个提示错误,就是 The superclass "javax.servlet.http.HttpServlet" was n ...

  4. idea配置checkstyle/findbugs/pmd插件

    前提条件:工程已导入idea 一,Findbugs/PMD/CheckStyles插件安装 打开settings的plugins,点击查找FindBugs-IDEA/PMDPlugin/CheckSt ...

  5. 关于JavaScript中0、空字符串、'0'是true还是false的总结

    最近被问到关于js中空字符串是true还是false得问题,一时间没想起来,现在在chrome的console面板上输出代码测试一下. "" == false 结果是true    ...

  6. python开发基础04-函数、递归、匿名函数、高阶函数、装饰器

    匿名函数 lamba lambda x,y,z=1:x+y+z 匿名就是没有名字 def func(x,y,z=1): return x+y+z 匿名 lambda x,y,z=1:x+y+z #与函 ...

  7. 了解 go 的 Context

    go 的 Context 一直对 go 的 Context 一知半解,不了解其用途,因此在这里着重了解一下 go 语言的 Context 飞雪无情的一个博文对 go 的 Context 讲的比较易懂一 ...

  8. AlertDialog 、SimpleDialog、 showModalBottomSheet、showToast 自定义 Dialog

    // AlertDialog .SimpleDialog.showModalBottomSheet.showToast // 使用showToast安装插件 https://pub.dev/packa ...

  9. Flutter 中的常见的按钮组件 以及自 定义按钮组件

    一.Flutter 中的按钮组件介绍   Flutter 里有很多的 Button 组件很多,常见的按钮组件有:RaisedButton.FlatButton.   IconButton.Outlin ...

  10. 寒假安卓app开发学习记录(5)

    第一个项目运行成功! 今天主要是看视频 ,学习Android项目的目录结构.大概学习了一个小时左右.然后在网上学习和对比eclipse上的目录,了解每个目录的功能是什么. 了解了Android项目的目 ...