首页 > 其他分享 >AOP实现日志打印

AOP实现日志打印

时间:2023-04-19 17:47:10浏览次数:46  
标签:joinPoint String 打印 private AOP import 日志 operationLog annotation

package com.youmu.framework.love.interfaces;

import java.lang.annotation.*;

/**
 * @Author: guodong
 * @CreateTime: 2023-04-19  16:38
 * @Description: 自定义注解日志类
 * @Version: 1.0
 */
@Documented
@Target(ElementType.METHOD)//注解的作用类型为方法
@Retention(RetentionPolicy.RUNTIME)//注解可在运行阶段被加载到Class对象中
public @interface SysLog {

    boolean isPrint() default false;

    /**
     * 日志等级:自己定,此处分为1-9
     */
    int level() default 0;

    /**
     * 方法描述,可使用占位符获取参数:{{tel}}
     */
    String detail() default "";



}
package com.youmu.framework.love.dtos;

import lombok.Data;

import java.util.Date;

/**
 * @Author: guodong
 * @CreateTime: 2023-04-19  16:59
 * @Description: TODO
 * @Version: 1.0
 */
@Data
public class OperationLog {

    private String id;

    private Date createTime;

    /**
     * 日志等级
     */
    private Integer level;
    /**
     * 被操作的对象
     */
    private String operationUnit;
    /**
     * 方法名
     */
    private String method;
    /**
     * 参数
     */
    private String args;
    /**
     * 操作人id
     */
    private String userId;
    /**
     * 操作人
     */
    private String userName;
    /**
     * 日志描述
     */
    private String describe;
    /**
     * 操作类型
     */
    private String operationType;
    /**
     * 方法运行时间
     */
    private Long runTime;
    /**
     * 方法返回值
     */
    private String returnValue;


}
package com.youmu.framework.love.config;

import com.alibaba.fastjson.JSON;
import com.youmu.framework.love.dtos.OperationLog;
import com.youmu.framework.love.interfaces.SysLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Author: guodong
 * @CreateTime: 2023-04-19  16:48
 * @Description: 打印日志信息
 * @Version: 1.0
 */
@Aspect
@Component
@Slf4j
public class SysLogAop {


    /**
     * 此处的切点是注解的方式,也可以用包名的方式达到相同的效果
     */
    @Pointcut("execution(* com.youmu.framework.love.controller.*.*(..))")
    public void operationLog() {
    }


    /**
     * 环绕增强,相当于MethodInterceptor
     */
    @Around("operationLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object res = null;
        long time = System.currentTimeMillis();
        try {
            res = joinPoint.proceed();
            time = System.currentTimeMillis() - time;
        } catch (Exception e) {
            log.error(">> doAround error:{}", e.getMessage(), e);
        } finally {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            SysLog sysLog = signature.getMethod().getAnnotation(SysLog.class);
            if (sysLog != null && sysLog.isPrint()) {
                addOperationLog(joinPoint, res, time);
            } else {
                res = joinPoint.proceed();
            }
        }
        return res;
    }

    private void addOperationLog(JoinPoint joinPoint, Object res, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        OperationLog operationLog = new OperationLog();
        operationLog.setRunTime(time);
        operationLog.setReturnValue(JSON.toJSONString(res));
        operationLog.setId(UUID.randomUUID().toString());
        operationLog.setArgs(JSON.toJSONString(joinPoint.getArgs()));
        operationLog.setCreateTime(new Date());
        operationLog.setMethod(signature.getDeclaringTypeName() + "." + signature.getName());
        operationLog.setUserId("#{currentUserId}");
        operationLog.setUserName("#{currentUserName}");
        SysLog annotation = signature.getMethod().getAnnotation(SysLog.class);
        if (annotation != null) {
            operationLog.setLevel(annotation.level());
            operationLog.setDescribe(getDetail(((MethodSignature) joinPoint.getSignature()).getParameterNames(), joinPoint.getArgs(), annotation));
        }
        log.info(">> addOperationLog:{}", operationLog);
    }

    /**
     * 对当前登录用户和占位符处理
     *
     * @param argNames   方法参数名称数组
     * @param args       方法参数数组
     * @param annotation 注解信息
     * @return 返回处理后的描述
     */
    private String getDetail(String[] argNames, Object[] args, SysLog annotation) {
        Map<Object, Object> map = new HashMap<>();
        for (int i = 0; i < argNames.length; i++) {
            map.put(argNames[i], args[i]);
        }

        String detail = annotation.detail();
        try {
            detail = "'" + "#{currentUserName}" + "'=》" + annotation.detail();
            for (Map.Entry<Object, Object> entry : map.entrySet()) {
                Object k = entry.getKey();
                Object v = entry.getValue();
                detail = detail.replace("{{" + k + "}}", JSON.toJSONString(v));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }


}
   @SysLog(isPrint = true, level = 0, detail = "获取推荐列表")
    public ResultMessage<List<RecommendResponseVO>> getRecommendList(@RequestBody RecommendRequestVO requestVO) {
        log.info(">> getRecommendList params:{}", JSONObject.toJSONString(requestVO));
        List<RecommendResponseVO> recommendResponseVOList = Lists.newArrayList();
        String result = "";
        try {
            result = HttpUtils.postData(url, null, JSONObject.toJSONString(requestVO));
            log.info(">> getRecommendList result:{}", result);
            recommendResponseVOList = JSONObject.parseArray(result, RecommendResponseVO.class);
        } catch (Exception e) {
            log.error(">> getRecommendList error:{}", e.getMessage(), e);
        }
        return new ResultMessage<>(recommendResponseVOList);
    }

springboot项目中使用AOP实现日志打印。

 

标签:joinPoint,String,打印,private,AOP,import,日志,operationLog,annotation
From: https://www.cnblogs.com/jelly12345/p/17334091.html

相关文章

  • 自定义注解+AOP实现参数校验
          转: https://www.cnblogs.com/mcj123/p/16842043.htmlhttps://www.cnblogs.com/fps2tao/p/13921207.html https://www.cnblogs.com/fps2tao/p/13921106.htmlhttps://www.cnblogs.com/fps2tao/p/13306246.html ......
  • 类中自定义函数并调用and使用钩子函数打印类中变量
    在一个类中自定义一个函数A,并在前向传播函数forword中调用这个函数假设您正在编写一个PyTorch模型,您可以按照以下方式在类中定义函数A,并在forward函数中调用它:importtorchimporttorch.nnasnnclassMyModel(nn.Module):def__init__(self):super(MyMod......
  • TFA-收集日志及分析
    下载https://support.oracle.com/epmos/faces/DocumentDisplay?_afrLoop=272133523880062&id=1513912.1&_afrWindowMode=0&_adf.ctrl-state=fghvcgapa_617a安装[root@rhel75~]#./ahf_setupAHFInstallerforPlatformLinuxArchitecturex86_64AHFIns......
  • 打印佛祖
    console.log(["%c(一)本代码提供三包服务(包阅读、包编译、包运行)不包熟","(二)本代码所有解释权归权归佛祖所有,禁止未开光盲目上线","(三)请严格按照保养手册对代码进行保养,本代码特点:","i.运行在风电、水电的机器上","......
  • 京东物流面单打印
    最近单位小商城上线,使用的京东物流,在订单和物流单的对接上效率有待提高,最后考虑我们自己打印“物流面单”,联系了当地工作人员,大概了解了对接流程:1、在京东物流开放平台上网上注册;2、创建应用时,选择“自研商家”,认证时要用到“月结编码或客户编号”,这个是重点; 3、使用应用的app......
  • 14.SpringAOP 编程
    SpringAOP编程课程目标代理设计模式Spring的环境搭建SpringIOC与AOPSpring事物与传播行为一、代理模式1.1概述代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理访问目标对象。这样好处:可以在目标对象实现的基础上,增强额外的功能操作。(扩......
  • LInux单机部署ELK日志收集
    LInux单机部署ELK日志收集一、环境准备centos7cpu:1核内存:8G#安装vim,wget,net-tools设置主机名:vim/etc/hosts127.0.0.1localhostlocalhost.localdomainlocalhost4localhost4.localdomain4::1localhostlocalhost.localdomainlocalhost6localhost6.local......
  • 小程序打印小票,复制功能,自定义导航栏
    //复制联系地址fnCopyAddress(){wx.setClipboardData({data:this.data.detailInfo.address,success:res=>{Util.errorShow('复制联系地址成功')}})},//打印小票fnPrintTicket(){let_this=this;......
  • cronolog工具切割nohup运行日志
    1.日志分割:随着JAVA服务线上运行,默认单个日志文件占用磁盘空间会越来越大,查看文件信息不方便,故需要对日志文件进行分割,这里借用第三方工具cronolog切割,因为网上有很多种切分方式,要么不行要么不好用。 2.安装cronologA.yum在线安装:yuminstall-ycronolog;B.rpm离......
  • 【Azure 应用服务】当在Azure App Service的门户上 Log Stream 日志无输出,需要如何操
    问题描述在AzureAppService的门户上LogStream日志无输出,需要如何操作让其输出ApplicationLogs呢?如下图所示:问题解答请注意,上图中提示说:Applicationlogsareswitchedoff. YoucanturnthemonusingtheAppServiceLogsSettings.应用日志关闭,可以通过AppServiceL......