springboot --AopLog

在项目 pom.xml 文件中添加依赖:

<!-- aop 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

<!-- 用于日志切面中,以 json 格式打印出入参 -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.primitives.Bytes;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
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.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Aspect
@Component
@EnableAspectJAutoProxy
@Slf4j
public class LogAop {
    // @Pointcut("@annotation(ExtendPoint)")     //ExtendPoint为自定义的注解
    @Pointcut("execution(* com.demo.wode.controller.*Controller.*(..))")   //表示controller目录下的所有类名包含Controller的类中所有的公有方法 
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        log.info("=======================aop log start====================================");

        Object[] args = joinPoint.getArgs();
        List<Object> logArgs = Arrays.asList(args).stream()
                .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))
                .collect(Collectors.toList());

        log.info("======request begin=====");
        log.info("url : {} ", request.getRequestURL());
        log.info("uri : {} ", request.getRequestURI());
        log.info("method : {} ", request.getMethod());
        log.info("param : {} ", JSON.toJSONString(logArgs));

        Object result;
        try {
            result = joinPoint.proceed();
            log.info("=====request end=====");
            log.info("result : {}", JSON.toJSONString(result));
        } catch (Exception e) {
            StackTraceElement[] stackTraceElements = e.getStackTrace();
            byte[] bytes = new byte[]{};
            for (StackTraceElement element : stackTraceElements) {
                byte[] byteArray = element.toString().getBytes();
                bytes = Bytes.concat(bytes, byteArray);
            }
            bytes = Bytes.concat(("*exception*" + e.getMessage() + "*exception*").getBytes(), bytes);
            e.printStackTrace();
            log.info("=======================aop log end with exception====================================");
            throw e;
        }
        log.info("=======================aop log end====================================");

        return result;
    }

}

 

第二种:
package com.gaoxi.handle;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author 大闲人柴毛毛
 * @Date 2017/10/29 下午12:58
 * REST接口统一的日志处理
 */
@ControllerAdvice
@ResponseBody
public class LogHandle {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(public * com.gaoxi.controller..*.*(..))")
    public void restLog(){}

    @Around("restLog()")
    public void doAround(ProceedingJoinPoint joinPoint) throws Throwable {

        // 生成本次请求时间戳
        String timestamp = System.currentTimeMillis()+"";

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        logger.info(timestamp + ", url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

        // result的值就是被拦截方法的返回值
        Object result = joinPoint.proceed();
        logger.info(timestamp + " , " + result.toString());
    }

}

 


 

posted @ 2019-07-31 10:33  不死码农  阅读(945)  评论(0编辑  收藏  举报