其他分享
首页 > 其他分享> > springBoot使用注解Aop实现日志模块

springBoot使用注解Aop实现日志模块

作者:互联网

我们在日常业务操作中需要记录很多日志,可以在我们需要的方法中对日志进行保存操作,但是对业务代码入侵性大。使用切面针对控制类进行处理灵活度不高,因此我们可以使用自定义注解来针对方法进行日志记录

1.注解

package com.infra.open.api.log;

import java.lang.annotation.*;

/**
 * 日志注解
 *
 * @Author : cgy
 * @Date : 2022/6/5
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
    /**
     * 接口名称
     *
     * @return
     */
    String interfaceName() default "";

    /**
     * 备注
     *
     * @return
     */
    String remark() default "";
}

2.切面类

package com.infra.open.api.log;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @Author : cgy
 * @Date : 2022/6/5
 */
@Slf4j
@Aspect
@Component
public class LogRecordAspect {

    @Pointcut("@annotation(com.infra.open.api.log.LogAnnotation)")
    public void pt() {
    }

    /**
     * 处理
     */
    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        //开始时间
        Long sTime = System.currentTimeMillis();
        //执行方法
        Object result = joinPoint.proceed();
        //结束时间
        Long eTime = System.currentTimeMillis();
        //处理日志
        handleLog(joinPoint, sTime, eTime);
        return result;
    }

    /**
     * 记录日志
     *
     * @param joinPoint
     * @param sTime
     * @param eTime
     */
    private void handleLog(ProceedingJoinPoint joinPoint, Long sTime, Long eTime) {
        //获取方法上面的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        //注解中的赋值
        String interfaceName = annotation.interfaceName();
        String remark = annotation.remark();

        System.out.println("注解中的值" + interfaceName + remark);

        //获取请求的方法地址
        String name = method.getName();
        System.out.println("name1" + name);
        String name1 = signature.getName();
        System.out.println("name2" + name1);
        String name2 = joinPoint.getTarget().getClass().getName();
        System.out.println("name3" + name2);


        //获取参数
        Object[] args = joinPoint.getArgs();
        System.out.println("args" + JSON.toJSONString(args[0]));

        //获取请求的ip地址
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        String ipAddr = IpUtils.getIpAddr(request);
        System.out.println("ip" + ipAddr);
    }
}

3.工具类

package com.infra.open.api.log;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author : cgy
 * @Date : 2022/6/5
 */
public class HttpContextUtil {
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}
package com.infra.open.api.log;

/**
 * @Author : cgy
 * @Date : 2022/6/5
 */

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpUtils {
    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST = "127.0.0.1";
    private static final String SEPARATOR = ",";

    public static String getIpAddr(HttpServletRequest request) {
        System.out.println(request);
        String ipAddress;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (LOCALHOST.equals(ipAddress)) {
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            // "***.***.***.***".length()
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(SEPARATOR) > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }
}

标签:String,request,System,Aop,import,日志,ipAddress,public,springBoot
来源: https://www.cnblogs.com/cgy1995/p/16343883.html