springboot+aop 切面编程 格式化日志格式

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-core</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>
package com.cjkj.log.monitor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @program: cjkj
 * @description:
 * @author: mr。zhang
 * @create: 2020-02-27 16:40
 **/
@Aspect
@Component
@Slf4j
public class LogAspect {
    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
    public void pointcutDef() {
    }

    /**
     * 声明环绕通知
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("pointcutDef()")
    public Object doAround(ProceedingJoinPoint pjp) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String classType = pjp.getTarget().getClass().getName();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期
        String date = df.format(new Date());
        String url = request.getRequestURL().toString();
        String methodName = pjp.getSignature().getName();
        String ipAddr = getRemoteHost(request);
        Object[] args = pjp.getArgs();
        String clazzName = "";
        String reqParams = "";
        Object result = null;
        try {
            clazzName = Class.forName(classType).getName();
            Object[] arguments = new Object[args.length];
            for (int i = 0; i < args.length; i++) {
        //此处是为了不让对httprequest等的序列化
                if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) {
                    continue;
                }
                arguments[i] = args[i];
            }
            if (arguments != null) {
                reqParams = JSONObject.toJSONString(arguments);
            }
            result = pjp.proceed();
        } catch (Throwable throwable) {
            log.info("time:【{}】,IP:【{}】,URL:【{}】,reqParams:【{}】,return:【{}】", date, ipAddr, url, reqParams, throwable);
        }
        String respParam = postHandle(result);
        log.info("time:【{}】,IP:【{}】,clazzName: 【{}】,methodName: 【{}】,URL:【{}】,reqParams:【{}】,return:【{}】", date, ipAddr, clazzName, methodName, url, reqParams, respParam);
        return result;
    }

    @AfterThrowing(pointcut = "pointcutDef()", throwing = "e")
    public void doThrowing(JoinPoint joinPoint, Exception e) {
        String methodName = joinPoint.getSignature().getName();

        Object[] args = joinPoint.getArgs();
        Map<String, String> params = (Map<String, String>) args[0];
        Object arg1 = args[1];
        log.error("methodName: 【{}】,reqParams: 【{}】, Stack Info: 【{}】,arg1",methodName, params,e.getMessage(),arg1);
    }

    /**
     * 返回数据
     *
     * @param retVal
     * @return
     */
    private String postHandle(Object retVal) {
        if (null == retVal) {
            return "";
        }
        return JSON.toJSONString(retVal);
    }


    /**
     * 获取目标主机的ip
     *
     * @param request
     * @return
     */
    private String getRemoteHost(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();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}

 

上边是我自己写的一个组件,也就是jar包,当我引入到其他项目的时候,发现并不能扫描到。百思不得其解,最后没办法,就在主项目的启动类上加上了扫描的注解以及扫描的路径:

@ComponentScan(basePackages = {"com.cjkj,com.cjkj.log.monitor"})

 

逗号前边的那个的那个路径是我主项目的路径,后边是我扫描jar包的位置。如果你不做成jar包的话  ,那就不需要这一步操作了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值