原创

SpringBoot全局日志配置


借助SpringAOP功能,我们可以将AOP应用至全局异常处理,全局请求拦截等,本篇文章的核心就是使用AOP实现操作日志输出,比如哪些用户进行了哪些操作,对于一个成功的项目这是必须记录的,下面给出一个简单模型应用:

一、引入相关jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
    <version>1.3.8.RELEASE</version>
</dependency>

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

二、编写切面类

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Aspect
@Component
public class WebLogAspect {
     //引入日志配置
    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

     /**
     * 定义一个切入点 只拦截controller.
     * 解释下:
     * ~ 第一个 * 代表任意修饰符及任意返回值.
     * ~ 第二个 * 定义在web包或者子包
     * ~ 第三个 * 任意方法
     * ~ .. 匹配任意数量的参数.
     */
    @Pointcut("execution(public * com.lee.test.controller.*.*(..))")
    public void webLog(){}
     //也可以将注解设置为切入点,这样就只会输出被注解方法的操作日志
    //将自定义注解设置为切点
    /*@Pointcut("@annotation(com.lee.test.annotation.MonitorLog)")
    public void webLog(){}*/

    //使用环绕通知输出整个操作前后日志
    @Around("webLog()")
    public Object doBefore(ProceedingJoinPoint jp) throws Throwable{
       // 接收到请求,取出请求域对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //打印请求的内容
        Long startTime = System.currentTimeMillis();
        log.info("请求Url : {}", request.getRequestURL().toString());
        log.info("请求方式 : {}", request.getMethod());
        log.info("请求ip : {}", getIpAddr(request));
        log.info("请求控制器 : {}", jp.getSignature().getDeclaringTypeName());
        log.info("请求方法 : {}", jp.getSignature().getName());
        log.info("请求参数 : {}", Arrays.toString(jp.getArgs()));
        // 执行方法
        Object result = jp.proceed();
        log.info("请求结束时间:" + LocalDateTime.now());
        log.info("请求耗时:{}", (System.currentTimeMillis() - startTime) + "ms");
        // 处理完请求,返回内容
        log.info("请求返回 : {}", result);
        return result;
    }

   //异常
   /*@AfterThrowing(value = "webLog()", throwing = "throwable")
    public void doAfterThrowing(Throwable throwable) {
        // 保存异常日志记录
        log.error("发生异常时间:{}", LocalDateTime.now());
        log.error("抛出异常:{}", throwable.getMessage());
    }*/

     /**
     * 描述 : 访问者ip的转换
     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}

三、补充(自定义注解及操作类型枚举)

定义一个枚举类,用来定义不同的操作

public enum LogEnum {

    UNOPERATE(0,"未定义操作"),
    SELECT(1,"查询"),
    INSERT(2,"添加"),
    UPDATE(3,"更新"),
    DELETE(4,"删除"),
    EXPORT(5,"excel导出"),
    LOGIN(6,"登陆"),
    LOGOUT(7,"登出"),
    ;
    LogEnum( Integer code, String operate) {
        this.operate = operate;
        this.code = code;
    }
    LogEnum(){}
    // 操作
    private String operate;
    // 操作码
    private Integer code;

    public String getOperate() {
        return operate;
    }
    public void setOperate(String operate) {
        this.operate = operate;
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
}

定义日志注解

@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MonitorLog {
    /* *
     * @Author lee
     * <p>日志内容 </p>
     * @Param []
     * @Return java.lang.String
     */
    String value() default "";

    /* *
     * @Author lee
     * <p>日志操作类型 </p>
     * @Param []
     * @Return int
     */
    LogEnum operateType() default LogEnum.UNOPERATE;
}

示例:

/**
 * 使用自定义注解,指定日志类容及操作类型
 */
@RestController
public class UserController {

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

    @MonitorLog(value="查询用户",operateType = LogEnum.SELECT)
    @GetMapping("test")
    public String getUser(String user){
        return "test";
    }
}
正文到此结束