SpringBoot配置使用Spring AOP日志记录

1、引入pom

        <!--springBoot的aop-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!--日志打印使用到 @Slf4j注解  方便又简单-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>    

关于@Slf4j IDEA无法显示import的问题

https://www.cnblogs.com/dzcici/p/12877551.html

目录结构

2、使用注解方式进行注明

LogAuditAspect.class
package com.dbcoding.mall.cms.aspect;

import com.dbcoding.mall.cms.aspect.annotation.SystemLogs;
import com.dbcoding.mall.cms.service.SellChannelAddressService;
import com.dbcoding.mall.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
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.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: AAA
 * @Description: TODO
 * @Author: Stephen.Zhang
 * @CreateDate: 2020-05-15 09:37
 * @Version: 1.0
 **/
@Aspect
@Component
@Slf4j
public class LogAuditAspect {
    private String LOG_AUDIT_MESSAGE = "log_audit.properties";
    @Autowired
    private SellChannelAddressService sellService;

    @Pointcut("@annotation(com.dbcoding.mall.cms.aspect.annotation.SystemLogs)")
    public void aspect() {
    }

    @After("aspect()")
    public void doAfter(JoinPoint joinPoint) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        Map<String, Object> map = getControllerMethodDescription(joinPoint);
        String key = (String) map.get("key");
        //String description = PropertiesUtil.getProperties(this.LOG_AUDIT_MESSAGE, key);
        log.info(key);//方法名备注  
        log.info(RequestUtil.getRealIp(request));//IP
        log.info(request.getRequestURI());//请求具体URL
        log.info(request.getMethod());//请求方法 GET...
    }

    @AfterThrowing(pointcut = "aspect()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        log.info("Enter the abnormal log...");
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                    .getRequest();
            Map<String, Object> map = getControllerMethodDescription(joinPoint);
            String key = (String) map.get("key");
            //String description = PropertiesUtil.getProperties(this.LOG_AUDIT_MESSAGE, key);
            log.info(key);//注解value值
            log.info(RequestUtil.getRealIp(request));//IP
            log.info(request.getRequestURI());//请求具体URL
            log.info(request.getMethod());//请求方法 GET...
            log.info(e.getMessage());//异常消息
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    private Map<String, Object> getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        Map<String, Object> map = new HashMap();
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    map.put("key", ((SystemLogs) method.getAnnotation(SystemLogs.class)).key());
                    break;
                }
            }
        }
        return map;
    }
}
SystemLogs
package com.dbcoding.mall.cms.aspect.annotation;

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

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({java.lang.annotation.ElementType.PARAMETER, java.lang.annotation.ElementType.METHOD})
public @interface SystemLogs {
    String key() default "";
}

RequestUtil.class

package com.dbcoding.mall.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

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

/**
 * @ClassName: AAA
 * @Description: TODO
 * @Author: Stephen.Zhang
 * @CreateDate: 2020-05-15 10:18
 * @Version: 1.0
 **/
@Slf4j
public class RequestUtil {
    public static int getPageid(HttpServletRequest request, String name) {
        int pageid = NumberUtils.toInt(request.getParameter(name));
        if (pageid <= 0) {
            return 1;
        }
        return pageid;
    }

    public static String getUrl(HttpServletRequest request) {
        StringBuffer sb = request.getRequestURL();
        String queryString = request.getQueryString();
        if (StringUtils.isNotEmpty(queryString)) {
            sb.append('?').append(queryString);
        }
        return sb.toString();
    }

    public static String getReferer(HttpServletRequest request) {
        return request.getHeader("referer");
    }

    public static String getRequestUri(HttpServletRequest request) {
        return request.getRequestURI();
    }

    private static final java.util.regex.Pattern IS_LICIT_IP_PATTERN = java.util.regex.Pattern.compile("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$");

    public static boolean isLicitIp(final String ip) {
        if (StringUtils.isEmpty(ip)) {
            return false;
        }

        Matcher m = IS_LICIT_IP_PATTERN.matcher(ip);
        if (!m.find()) {
            return false;
        }
        return true;
    }

    public static boolean isSsl(HttpServletRequest request) {
        boolean isSsl = "true".equalsIgnoreCase(request.getHeader("ssl"));
        return isSsl;
    }

    public static String getProtocol(HttpServletRequest request) {
        boolean isSsl = RequestUtil.isSsl(request);
        String protocol;
        if (isSsl) {
            protocol = "https";
        } else {
            protocol = "http";
        }
        return protocol;
    }

    public static String getRedirect(HttpServletRequest request, String url) {
        if (StringUtils.isEmpty(url)) {
            log.error("url parameters can not be null.");
            throw new NullPointerException("url parameters can not be null.");
        }
        if (url.startsWith("http")) {
            return url;
        }
        boolean isSsl = RequestUtil.isSsl(request);
        if (!isSsl) {
            return url;
        }
        if (!url.startsWith("/")) {
            String path = request.getServletPath();
            int index = path.lastIndexOf('/');
            if (index != -1) {
                url = path.substring(0, index + 1) + url;
            }
        }
        String serverName = request.getServerName();

        return "https://" + serverName + url;
    }

    @SuppressWarnings("unchecked")
    public static void printHeaders(HttpServletRequest request) {
        Enumeration<String> e = request.getHeaderNames();
        while (e.hasMoreElements()) {
            String name = e.nextElement();
            String value = request.getHeader(name);
            log.info(name + ":" + value);
        }
    }

    /**
     * 获取真实客户端IP
     *
     * @param request
     * @return
     */
    public static String getRealIp(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();
        }

        int index = ip.lastIndexOf(',');
        if(index <= 0) {
            index = ip.length();
        }
        String lastip = ip.substring(0, index).trim();

        if ("127.0.0.1".equals(lastip) || !isLicitIp(lastip)) {
            return request.getRemoteAddr();
        }

        return lastip;
    }
}

3、使用

 
原文地址:https://www.cnblogs.com/dzcici/p/12893599.html