Spring Aop整合log4j2分类打印日志

1.参考地址

(1)log4j2配置:Springboot整合log4j2日志全解
(2)Spring Aop:spring-aop切面知识

2.引入Aop相关jar包

(1)SpringBoot需引入的jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency> 
3.Spring Aop 打印日志

(1)创建日志切面注解

import java.lang.annotation.*;

/**
 * 日志切面注解
 *
 * @author xxx (created on xxxx-xx-xx)
 * @version 1.0
 */
@Retention(RetentionPolicy.RUNTIME) //什么时候使用该注解,我们定义为运行时
@Target({ElementType.METHOD}) //注解用于什么地方,我们定义为作用于方法上
@Documented //注解是否将包含在 JavaDoc 中
public @interface MethodLog {
    String description() default "";
}

(2)创建Aop日志打印实现类

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * Aop 日志打印
 *
 * @author xxx (created on xxxx-xx-xx)
 * @version 1.0
 */
@Aspect
@Component
public class LogService {
	
	private static final Logger logger = LoggerFactory.getLogger("user");

    @Pointcut("@annotation(xxx.aop.annotation.MethodLog)")
    public void printMsg() {

    }

    @Around("printMsg()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String requestMethod = request.getMethod().toUpperCase();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = proceedingJoinPoint.getSignature().getDeclaringTypeName() + "." + proceedingJoinPoint.getSignature().getName();
        if (RequestMethod.GET.name().equals(requestMethod)) {
            return null;
        }
        Admin admin = null;
        ArrayList<Object> argList = new ArrayList<>();
        for (Object arg : proceedingJoinPoint.getArgs()) {
            // request/response无法使用toJSON
            if (arg instanceof HttpServletRequest) {
                argList.add("request");
            } else if (arg instanceof HttpServletResponse) {
                argList.add("response");
            } else if (arg instanceof Admin) {
                admin = (Admin) arg;
                argList.add("admin:" + JSON.toJSONString(admin));
            } else {
                argList.add(arg);
            }
        }

        //获取@MethodLog注解的描述信息
        String methodDescription = getAspectLogDescription(proceedingJoinPoint);
        Object result = proceedingJoinPoint.proceed();
        String resultStr = JSON.toJSONString(result);
        
        logger.info("【{}】{}\nRequest URL:{}\nHTTP Method:{}\nIP:{}\nClass Method:{}\n请求参数:{}\n结果:{}\n",
                methodDescription, admin.getAccount(), url, requestMethod, ip, classMethod, argList, resultStr);
        return result;
    }

    /**
     * 获取切面注解的描述
     */
    private String getAspectLogDescription(ProceedingJoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazz = method.getParameterTypes();
                if (clazz.length == arguments.length) {
                    description.append(method.getAnnotation(MethodLog.class).description());
                    break;
                }
            }
        }
        return description.toString();
    }
}

(3)Aop注解使用

@MethodLog(description = "合同审批")
public Result test(Admin admin, Integer count) {
	return new Result(true, "测试方法");
}

文章内容仅代表个人观点,如有不正之处,欢迎批评指正,谢谢大家。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值