ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-06-05 14:33:13  阅读:143  来源: 互联网

标签:String request System Aop import 日志 ipAddress public springBoot


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

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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有