首页 > 数据库 >自定义日志注解,保存信息到数据库

自定义日志注解,保存信息到数据库

时间:2024-09-18 20:22:02浏览次数:3  
标签:String 自定义 joinPoint 保存信息 sysLog org import 日志 annotation

定义日志注解

import java.lang.annotation.*;

/**
 * @author wzw
 * @version 1.0
 * @Date 2023-2-17 17:31:19
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {

    /**
     * 描述
     * @return
     */
    String desc();


    boolean isSaveLog() default true;

}

定义切面

定义切面,在使用了指定注解的方法执行前后,进行操作,这里是用来在使用了自定义注解的方法执行完,保存日志信息 UserBean是测试系统的用户实体,BusinessLogs 是测试系统的日志实体,直接删掉就可以了

import com.alibaba.fastjson.JSON;
import com.weeon.platform.common.bean.UserBean;
import com.weeon.platform.common.dao.BusinessLogsDao;
import com.weeon.platform.common.domain.BusinessLogs;
import com.weeon.platform.common.utils.HttpRequestUtils;
import com.weeon.platform.common.utils.PrimaryKeyUtils;
import com.weeon.platform.common.utils.WebUserUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author wzw
 * @version 1.0
 * @Date 2023-2-17 17:31:19
 */
@Aspect
@Component
public class LogPoint {

    @Resource
    private BusinessLogsDao businessLogsDao;

    //配置织入点
    @Pointcut("@annotation(com.weeon.platform.api.log.Log)")
    public void logPointCut() {

    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint  切点
     * @param jsonResult 返回的信息
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterRetuning(JoinPoint joinPoint, Object jsonResult) {
        Log annotationLog = getAnnotationLog(joinPoint);
        if(annotationLog.isSaveLog()){
            handleLog(joinPoint, null, jsonResult);
        }
    }

    /**
     * 处理完请求之后执行
     *
     * @param joinPoint  切点
     * @param e          异常信息
     * @param jsonResult 返回结果
     */
    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {

        UserBean userBean = WebUserUtils.getUser();

        Log controllerLog = getAnnotationLog(joinPoint);
        if (controllerLog == null) {
            return;
        }

        BusinessLogs sysLog = new BusinessLogs();
        sysLog.setId(PrimaryKeyUtils.getId());

        // 请求的地址
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) attributes;
        HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();

        //请求参数
        Map<String, String[]> param = ((ServletRequestAttributes) attributes).getRequest().getParameterMap();
        String s = JSON.toJSONString(param);
        s=s.replaceAll("(\\[)|(\\])","");
        sysLog.setParvalue(s);
        sysLog.setUrl(HttpRequestUtils.getRequestUrl(request) + " " + request.getMethod());

        //操作用户信息
        sysLog.setUserid(userBean.getUserid());
        sysLog.setUsername(userBean.getUsername());
        sysLog.setZtid(userBean.getZtid());
        sysLog.setZtcode(userBean.getZtcode());
        sysLog.setZtname(userBean.getZtname());
        String ip = HttpRequestUtils.getIp(request);
        sysLog.setIp(ip);

        // 设置方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        sysLog.setClassname("类名:" + className + " 方法:" + methodName + "()");

        //日志描述
        sysLog.setDescription(controllerLog.desc());

        // 保存到数据库
        businessLogsDao.save(sysLog);

    }

    /**
     * 是否存在注解,如果存在就获取
     *
     * @param joinPoint 切点
     * @return 注解对象
     */
    private Log getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }


}

使用

@Log(desc = "访问了/testhandler/test1路径",isSaveLog = false)
    @RequestMapping("/testhandler/test1")
    public String test1(){


        return "123";
    }

其它

获取调用者类名和方法名

String className = new Exception().getStackTrace()[1].getClassName(); //获取调用者的类名
        String methodName = new Exception().getStackTrace()[1].getMethodName(); //获取调用者的方法名

切点

  • 使用@annotation(annotation)作为切点表达式,表示拦截所有带有指定注解的方法。
@AfterReturning(pointcut = "@annotation(Log)")
public void doAfterReturning(JoinPoint joinPoint, Log log) {
    // 处理日志
}
  • 使用@target(target)作为切点表达式,表示拦截所有指定类型的方法。
@AfterReturning(pointcut = "@target(Controller)")
public void doAfterReturning(JoinPoint joinPoint, Controller controller) {
    // 处理日志
}
  • 使用@within(within)作为切点表达式,表示拦截所有指定类型的类的方法。
@AfterReturning(pointcut = "@within(Service)")
public void doAfterReturning(JoinPoint joinPoint, Service service) {
    // 处理日志
}
  • 使用@args(args)作为切点表达式,表示拦截所有带有指定参数的方法。
@AfterReturning(pointcut = "@args(String)")
public void doAfterReturning(JoinPoint joinPoint, String arg) {
    // 处理日志
}
  • 使用@annotation(annotation)和@target(target)、@within(within)、@args(args)组合使用,表示拦截所有带有指定注解、指定类型、指定类型的类的方法、带有指定参数的方法。
@AfterReturning(pointcut = "@annotation(Log) && @target(Controller) && @args(String)")
public void doAfterReturning(JoinPoint joinPoint, Log log, Controller controller, String arg) {
    // 处理日志
}

标签:String,自定义,joinPoint,保存信息,sysLog,org,import,日志,annotation
From: https://blog.51cto.com/u_16390833/12048521

相关文章

  • wpf简单自定义控件
    用户控件(UserControl)和自定义控件(CustomControl)的区别:UserControl:将多个WPF控件(例如:TextBox,TextBlock,Button)进行组合成一个可复用的控件组;由XAML和CodeBehind代码组成;不支持样式/模板重写;CustomControl自定义控件,扩展自一个已经存在的控件,并添加新的功能/特性;由C......
  • 《鸿蒙/Harmony | 开发日志》图片压缩
    一般在做APP头像、背景等功能的时候,调用系统选择图片功能,上传给服务端,图片都非常的大,相机像素越高图片就越大。一般都有几M,甚至10M以上的,这个时候一般需要压缩图片,变成非常小的图片,如果不压缩图片,将几M的图片作为头像,用户访问个头像发现下载要个1-2秒,就体验非常差。压缩......
  • 自定义类型:联合和枚举
    目录引言一.联合体1.1联合体的定义1.2联合体的声明 1.3 联合体的特点1.4相同成员的结构体和联合体对比1.5联合体大小的计算1.6联合体的作用1.7联合体的小练习二.枚举类型 2.1枚举的定义2.2枚举的声明2.3枚举的作用2.4枚举的使用示例 后记引言......
  • Shader Graph自定义渐变色节点Gradiant
    ShaderGraph自定义渐变色节点GradiantUnity自带Shader中的Gradiant不能暴露在外部使用定义CustomFunction来制作暴露给外部的GradiantShaderGraph节点图CustomFunction代码if(inputValue<location1){outFloat=color1;}else......
  • laravel: 日志配置
    一,日志按天切分:修改.envroot@lhdpc:/data/api#vi.env指定LOG_CHANNEL值为daily即可,代码:LOG_CHANNEL=daily二,配置laravel日志中记录url/方法/参数1,config/logging.php'daily'=>['driver'=>'daily','path......
  • 自定义浏览器滚动条样式
    自定义浏览器滚动条样式Webkit内核的浏览器,可以通过-webkit-scrollbar等属性进行重置/*设置尺寸*/::-webkit-scrollbar{width:10px;height:10px;}/*滚动条两端的按钮*/::-webkit-scrollbar-button{background-color:red;width:100px;height:10px;}......
  • PyQt / PySide + Pywin32 + ctypes 自定义标题栏窗口 + 完全还原 Windows 原生窗口边
    项目地址:GitHub-github201014/PyQt-NativeWindow:AclassofwindowincludenativeEvent,usePySideorPyQtandPywin32andctypesAclassofwindowincludenativeEvent,usePySideorPyQtandPywin32andctypes-github201014/PyQt-NativeWindowhttps://githu......
  • Docker限制日志文件大小及个数
    对单个容器生效dockerrun--log-optmax-size=10m--log-optmax-file=3全局容器生效vim/etc/docker/daemon.json{"log-driver":"json-file","log-opts":{"max-size":"200m","max-file"......
  • VUE框架CLI组件化组件绑定自定义事件时回调函数的this对象------VUE框架
    <template> <div> <!--内置函数的实现步骤--> <!--提供事件源,给事件源绑定事件,编写回调函数,将回调函数和事件进行绑定--> <!--等待事件的触发,事件触发执行回调函数--> <!--组件的自定义事件实现步骤--> <button@click="Hello()">你好</button> <!--给Us......
  • Vue自定义指令以及项目中封装过的自定义指令
     自定义指令Vue 自定义指令是Vue.js框架中一个非常强大的功能,它允许你注册一些全局或局部的自定义DOM操作指令,以便在模板中复用。自定义指令通过Vue.directive()方法进行全局注册,或者在组件的directives选项中局部注册。自定义指令的钩子函数Vue自定义指令可以包含几个......