zoukankan      html  css  js  c++  java
  • Springboot AOP写操作日志 GET POST

    pom.xml

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-aop</artifactId>
            </dependency>
    
            <dependency>
                <groupId>com.google.code.gson</groupId>
                <artifactId>gson</artifactId>
                <version>2.8.1</version>
    </dependency>
    

    SysLog.java

    import java.lang.annotation.*;
    
    /**
     * 定义系统日志注解
     * @author zhuzhe
     * @date 2018/6/4 9:24
     * @email 1529949535@qq.com
     */
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface SysLog {
        String value() default "";
    }
    
    

    SysLogAspect.java

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.serializer.SerializerFeature;
    import com.cicso.jenkins.entity.TLoggerInfos;
    import com.cicso.jenkins.service.TLoggerInfosService;
    import com.google.gson.Gson;
    import lombok.extern.slf4j.Slf4j;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.aspectj.lang.reflect.MethodSignature;
    import org.springframework.beans.factory.annotation.Autowired;
    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 org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import java.lang.reflect.Method;
    import java.net.URLDecoder;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    import static org.apache.commons.lang.CharEncoding.UTF_8;
    
    /**
     * 系统日志切面
     * @author zhuzhe
     * @date 2018/6/4 9:27
     * @email 1529949535@qq.com
     */
    @Aspect  // 使用@Aspect注解声明一个切面
    @Component
    @Slf4j
    public class SysLogAspect {
    
        @Autowired
        private TLoggerInfosService tLoggerInfosService;
    
        /**
         * 这里我们使用注解的形式
         * 当然,我们也可以通过切点表达式直接指定需要拦截的package,需要拦截的class 以及 method
         * 切点表达式:   execution(...)
         */
        @Pointcut("@annotation(com.cicso.jenkins.config.SysLog)")
        public void logPointCut() {}
    
    
        @Before("logPointCut()")
        public void exBefore(JoinPoint pjp){
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();
            long startTime = System.currentTimeMillis();
            request.setAttribute("startTime",startTime);
        }
    
        /**
         * 环绕通知 @Around  , 当然也可以使用 @Before (前置通知)  @After (后置通知)
         * @param point
         * @return
         * @throws Throwable
         */
        @Around("logPointCut()")
        public Object around(ProceedingJoinPoint point) throws Throwable {
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletRequest request = sra.getRequest();
            long endTime = System.currentTimeMillis();
    //        String url = request.getRequestURL().toString();
            String method = request.getMethod();
            String uri = request.getRequestURI();
            String queryString = request.getQueryString();
            Object[] args = point.getArgs();
            String params = "";
            // result的值就是被拦截方法的返回值
            Object result = point.proceed();
            try {
                long startTime = (long) request.getAttribute("startTime");
                //获取请求参数集合并进行遍历拼接
                if (args.length > 0) {
                    if ("POST".equals(method)) {
                       /* Object object = args[0];
                        params = JSON.toJSONString(object, SerializerFeature.WriteMapNullValue);*/
                        Object[] arguments  = new Object[args.length];
                        for (int i = 0; i < args.length; i++) {
                            if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                                //ServletRequest不能序列化,从入参里排除,否则报异常:java.lang.IllegalStateException: It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)
                                //ServletResponse不能序列化 从入参里排除,否则报异常:java.lang.IllegalStateException: getOutputStream() has already been called for this response
                                continue;
                            }
                            arguments[i] = args[i];
                        }
                        if (arguments != null) {
                            try {
                                params = JSONObject.toJSONString(arguments);
                            } catch (Exception e) {
                                params = arguments.toString();
                            }
                        }
                    } else if ("GET".equals(method)) {
                        params = queryString;
                    }
                    params = URLDecoder.decode(params,UTF_8);
                }
                log.info("requestMethod:{},url:{},params:{},responseBody:{},elapsed:{}ms.", method , uri,  params,
                        JSON.toJSONString(result,SerializerFeature.WriteMapNullValue),(endTime - startTime));
            }catch (Exception e){
                e.printStackTrace();
                log.error("log error !!",e);
            }
            return result;
        }
    }
    
    
    

    Response.java

    package com.cicso.jenkins.utils;
    
    import com.fasterxml.jackson.databind.annotation.JsonSerialize;
    import lombok.Getter;
    import lombok.Setter;
    
    import java.io.Serializable;
    
    /**
     * 请求返回类
     * Created by Tiger on 2018/10/9.
     */
    @Getter
    @Setter
    @JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
    public class Response<T> implements Serializable {
    
        private static final long serialVersionUID = -4505655308965878999L;
    
        //请求成功返回码为:0000
        private static final String successCode = "200";
        //返回数据
        private T data;
        //返回码
        private String code;
        //返回描述
        private String msg;
    
        public Response(){
            this.code = successCode;
            this.msg = "success";
        }
    
        public Response(String code,String msg){
            this();
            this.code = code;
            this.msg = msg;
        }
        public Response(String code,String msg,T data){
            this();
            this.code = code;
            this.msg = msg;
            this.data = data;
        }
        public Response(T data){
            this();
            this.data = data;
        }
    }
    

    UserController.java

    package com.cicso.jenkins.controller;
    
    import com.cicso.jenkins.config.SysLog;
    import com.cicso.jenkins.entity.JenkinsCiLog;
    import com.cicso.jenkins.entity.JenkinsMonitor;
    import com.cicso.jenkins.entity.User;
    import com.cicso.jenkins.service.JenkinsCiLogService;
    import com.cicso.jenkins.service.JenkinsMonitorService;
    import com.cicso.jenkins.service.UserService;
    import com.cicso.jenkins.utils.Response;
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpRequest;
    import org.springframework.web.bind.annotation.*;
    
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * @Description
     * @Author sgl
     * @Date 2018-05-02 14:59
     */
    @RestController
    public class UserController {
        @PostMapping("/postData")
        @SysLog("postData")
        public Response postData(HttpServletRequest httpRequest, @RequestBody JenkinsCiLog jenkinsCiLog) {
            return new Response();
        }
    
        @GetMapping("/users")
        @SysLog("lists")
        public Response lists(@RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize) {
            PageHelper.startPage(pageNo,pageSize);
            PageInfo<User> pageInfo = new PageInfo<>(userService.getUsers());
            return new Response(pageInfo);
        }
    
    }
    
    

    测试结果 console

    -2019-07-26 09:44:14.407 - INFO 24236 --- [nio-8888-exec-1] com.cicso.jenkins.config.SysLogAspect    : requestMethod:GET,url:/jenkinsApi/users,params:pageNo=1&pageSize=10,responseBody:{"code":"200","data":{"endRow":5,"firstPage":1,"hasNextPage":false,"hasPreviousPage":false,"isFirstPage":true,"isLastPage":true,"lastPage":1,"list":[{"userAge":27,"userId":1,"userName":"张三"},{"userAge":30,"userId":2,"userName":"李四"},{"userAge":20,"userId":3,"userName":"王五"},{"userAge":null,"userId":123,"userName":"Tian"},{"userAge":null,"userId":234,"userName":"San"}],"navigateFirstPage":1,"navigateLastPage":1,"navigatePages":8,"navigatepageNums":[1],"nextPage":0,"pageNum":1,"pageSize":10,"pages":1,"prePage":0,"size":5,"startRow":1,"total":5},"msg":"success"},elapsed:0ms.
    -3FCFE828206F320092C49A320E3C131A
    2019-07-26 09:44:18.323 - INFO 24236 --- [nio-8888-exec-2] com.cicso.jenkins.config.SysLogAspect    : requestMethod:POST,url:/jenkinsApi/postData,params:[null,{"actiontype":"string","buildTag":"string","buildUrl":"string","data":"string","id":0,"phasetype":"string","requestTime":1564102810254,"startTime":1564102810254}],responseBody:{"code":"200","data":null,"msg":"success"},elapsed:0ms.
    
  • 相关阅读:
    升级山狮系统后的几个问题
    Linux vim编辑命令总结
    css中float left与float right的使用说明
    如何利用MAMP架站 在Mac上架設WordPress
    解决mysql“Access denied for user 'root'@'localhost'”
    smarty strftime() error
    mac版本dreamweaver如何修改JS文件的编码
    例子:Read content from file to Arraylist
    MongoDB01 Introduction 介绍
    Login failed for user 'sa' because the account is currently locked out. The system administrator can unlock it.
  • 原文地址:https://www.cnblogs.com/zhizhao/p/11248437.html
Copyright © 2011-2022 走看看