springboot利⽤线程池异步记录⽇志(⼆)缘由
在业务逻辑中记录⽇志,繁琐且耦合度⾼,利⽤aop结合注解形式,更便捷
步骤
1.⾃定义【⽇志记录】注释
2.⾃定义⽇志记录实体类
3.利⽤aop,拦截被注释的⽅法,整理⽇志数据,插⼊数据库
ps:原理很简单,跟着代码读⼀遍就ok了
/**
* ⾃定义⽇志记录注释
* /
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log
{
/**
* 模块
*/
public String title() default "";
/**
* 功能
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
* 操作⼈类别
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
}
* ⾃定义的⽇志数据实体类
* /
public class SysOperLog extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** ⽇志主键 */
@Excel(name = "操作序号", cellType = ColumnType.NUMERIC)
private Long operId;
/** 操作模块 */
@Excel(name = "操作模块")
private String title;
/** 业务类型(0其它 1新增 2修改 3删除) */
@Excel(name = "业务类型", readConverterExp = "0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导⼊,7=强退,8=⽣成代码,9=清空数据")    private Integer businessType;
/** 业务类型数组 */
private Integer[] businessTypes;
springboot aop/** 请求⽅法 */
@Excel(name = "请求⽅法")
private String method;
/** 请求⽅式 */
@Excel(name = "请求⽅式")
private String requestMethod;
/** 操作类别(0其它 1后台⽤户 2⼿机端⽤户) */
@Excel(name = "操作类别", readConverterExp = "0=其它,1=后台⽤户,2=⼿机端⽤户")
private Integer operatorType;
/** 操作⼈员 */
@Excel(name = "操作⼈员")
private String operName;
/** 部门名称 */
@Excel(name = "部门名称")
private String deptName;
.......
}
/**
* 针对⾃定义的log注释,实现aop拦截
* 在内部整理⽇志参数,插⼊到数据库,实现⽇志记录
* /
@Aspect
@Component
public class LogAspect
{
private static final Logger log = Logger(LogAspect.class);
// 配置织⼊点
@Pointcut("@annotation(com.ruoyi.framework.aspectj.lang.annotation.Log)")
public void logPointCut()
{
}
/**
* 处理完请求后执⾏
*
* @param joinPoint 切点
@AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
{
handleLog(joinPoint, null, jsonResult);
}
/**
* 拦截异常操作
* 主要看的就是这个⽅法
* 其中⽇志记录的⽅法结合了上⼀篇⽂章的异步线程操作
* 也就是说,在⽇志数据插⼊数据库的这个过程,是由新创建的⼀个线程去执⾏的
* 这样⽇志记录中像与mysql交互这样耗时的操作,就不会耗费主线程的时间了
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "logPointCut()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e)
{
handleLog(joinPoint, e, null);
}
protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult)
{
try
{
// 获得注解
Log controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null)
{
return;
}
// 获取当前的⽤户
LoginUser loginUser = Bean(TokenService.class).Request());
// *========数据库⽇志=========*//
SysOperLog operLog = new SysOperLog();
operLog.setStatus(dinal());
// 请求的地址
String ip = Request());
operLog.setOperIp(ip);
// 返回参数
operLog.JSONString(jsonResult));
operLog.Request().getRequestURI());
if (loginUser != null)
{
operLog.Username());
}
if (e != null)
{
operLog.setStatus(dinal());
operLog.setErrorMsg(StringUtils.Message(), 0, 2000));
}
/
/ 设置⽅法名称
String className = Target().getClass().getName();
String methodName = Signature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 设置请求⽅式
operLog.Request().getMethod());
// 处理设置注解上的参数
getControllerMethodDescription(joinPoint, controllerLog, operLog);
// 保存数据库
<().dOper(operLog));
}
catch (Exception exp)
{
// 记录本地异常⽇志
<("==前置通知异常==");
<("异常信息:{}", Message());
exp.printStackTrace();
}
}
/**
* 获取注解中对⽅法的描述信息⽤于Controller层注解
*
* @param log ⽇志
* @param operLog 操作⽇志
* @throws Exception
*/
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog) throws Exception
{
// 设置action动作
operLog.setBusinessType(log.businessType().ordinal());
// 设置标题
operLog.setTitle(log.title());
// 设置操作⼈类别
operLog.setOperatorType(log.operatorType().ordinal());
// 是否需要保存request,参数和值
if (log.isSaveRequestData())
{
// 获取参数的信息,传⼊到数据库中。
setRequestValue(joinPoint, operLog);
}
}
/**
* 获取请求的参数,放到log中
*
* @param operLog 操作⽇志
* @throws Exception 异常
*/
private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception
{
String requestMethod = RequestMethod();
if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))
{
String params = Args());
operLog.setOperParam(StringUtils.substring(params, 0, 2000));
}
else
{
Map<?, ?> paramsMap = (Map<?, ?>) Request().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);            operLog.setOperParam(StringUtils.String(), 0, 2000));
}
}
/**
* 是否存在注解,如果存在就获取
*/
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
{
Signature signature = Signature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = Method();
if (method != null)
{
Annotation(Log.class);
}
return null;
}
/**
* 参数拼装
*/
private String argsArrayToString(Object[] paramsArray)
{
String params = "";
if (paramsArray != null && paramsArray.length > 0)
{
for (int i = 0; i < paramsArray.length; i++)
{
if (!isFilterObject(paramsArray[i]))
{
Object jsonObj = JSON(paramsArray[i]);
params += String() + " ";
}
}
}
im();
}
/**
* 判断是否需要过滤的对象。
*
* @param o 对象信息。
* @return 如果是需要过滤的对象,则返回true;否则返回false。
*/
public boolean isFilterObject(final Object o)
{
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;    }
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。