java使用AOP打印日志

一、创建一个自定义注解:

package com.yan.demo.core.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({
     ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Logging {
     
    String value() default "";
}

二、创建一个切面类

package com.yan.demo.core.aspect;

import com.alibaba.fastjson.JSONObject;
import com.wmeimob.fastboot.util.web.IpAddressHelper;
import java.math.BigDecimal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
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.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;

@Aspect
@Component
public class LoggingAspect {
     
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public LoggingAspect() {
     
    }

	//切点
    @Pointcut("@within(com.yan.demo.core.annotation.Logging)")
    public void loggingAspect() {
     
    }

    @Before("loggingAspect()")
    public void before(JoinPoint joinPoint) {
     
        if (this.logger.isDebugEnabled()) {
     
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            StringBuilder params = new StringBuilder();
            if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
     
                for(int i = 0; i < joinPoint.getArgs().length; ++i) {
     
                    params.append(joinPoint.getArgs()[i]).append(";");
                }
            }

            StringBuffer sb = new StringBuffer();
            sb.append("\n请求IP:").append(IpAddressHelper.getRemoteHost(request)).append("\n");
            sb.append("请求方法: ").append(joinPoint.getTarget().getClass().getName()).append(".").append(joinPoint.getSignature().getName()).append("()\n");
            sb.append("请求参数: ").append("".equals(params.toString()) ? "无" : params.toString()).append("\n");
            this.logger.info(sb.toString());
            this.logger.info("execute method ==>>{}()", joinPoint.getSignature().getName());
        }

    }

    @Around("loggingAspect()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
     
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        this.logger.debug("*******************函数START*********************");
        long start = System.currentTimeMillis();
        Object obj = pjp.proceed(pjp.getArgs());
        long end = System.currentTimeMillis();
        BigDecimal second = (new BigDecimal(end)).subtract(new BigDecimal(start)).divide(new BigDecimal("1000")).setScale(2, 4);
        String time = second + "秒";
        this.logger.debug("-------------------执行时间:" + time + "----------------------");
        if (second.doubleValue() > 1.0D) {
     
            this.logger.warn("execute method timeout!!!");
        }

        this.logger.debug("*******************函数END***********************\n");
        return obj;
    }

    @AfterThrowing(
        pointcut = "loggingAspect()",
        throwing = "e"
    )
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
     
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = IpAddressHelper.getRemoteHost(request);
        String params = "\n";
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
     
            for(int i = 0; i < joinPoint.getArgs().length; ++i) {
     
                if (!(joinPoint.getArgs()[i] instanceof HttpServletRequest) && !(joinPoint.getArgs()[i] instanceof HttpServletResponse)) {
     
                    params = params + JSONObject.toJSONString(joinPoint.getArgs()[i]) + "\n";
                }
            }
        }

        StringBuffer sb = new StringBuffer();
        sb.append("\n===================异常通知START==================\n");
        sb.append("异常方法:" + joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()\n");
        sb.append("请求IP:" + ip + "\n");
        sb.append("请求参数:" + params + "\n");
        sb.append("异常类名:" + e.getClass().getName() + "\n");
        sb.append("异常信息:" + e.getMessage() + "\n");
        sb.append("===================异常通知END====================\n");
        this.logger.error(sb.toString());
    }
}

三、使用

在需要打印日志的方法上添加@Logging注解

AOP使用详解点这里

你可能感兴趣的:(代码片段)