SpringBoot中通过AOP整合日志文件

1.SpringBoot中通过AOP整合日志文件

1.导入相关的依赖

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions> <!-- 去掉springboot自带的日志,不然会冲突 -->
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
    </dependency>
    <!-- log4j-api -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
    </dependency>
    <!-- log4j-slf4j-impl -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
    </dependency>
    <!-- slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
    </dependency>
    <!-- slf4j-simple 解决冲突-->
    <!--<dependency>-->
        <!--<groupId>org.slf4j</groupId>-->
        <!--<artifactId>slf4j-simple</artifactId>-->
    <!--</dependency>-->

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
</dependencies>

2.log4j2 日志文件

<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration 后面的 status 用于设置 log4j2 自身内部的信息输出,可以不设置,当设置成 trace 时,可以看到 log4j2 内部各种详细输出-->
<configuration status="INFO">
    <!--先定义所有的 appender-->
    <appenders>
        <!--输出日志信息到控制台-->
        <console name="Console" target="SYSTEM_OUT">
            <!--控制日志输出的格式-->
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </console>
    </appenders>
    <!--然后定义 logger,只有定义 logger 并引入的 appender,appender 才会生效-->
    <!--root:用于指定项目的根日志,如果没有单独指定 Logger,则会使用 root 作为默认的日志输出-->
    <loggers>
        <root level="info">
            <appender-ref ref="Console"/>
        </root>
    </loggers>
</configuration>

3.dao层的接口以及实现类

文件路径:com.dzj.dao.Userdao.java

package com.dzj.dao;

public interface Userdao {

    void add();

    void update();

    void delete();

    void query();
}

文件路径:com.dzj.dao.UserDaoImpl.java

package com.dzj.dao;

import org.springframework.stereotype.Service;

@Service
public class UserDaoImpl implements Userdao {
    @Override
    public void add() {
        System.out.println("执行了添加方法...");
    }

    @Override
    public void update() {

        System.out.println("执行了修改方法...");
    }

    @Override
    public void delete() {

        System.out.println("执行了删除方法...");
    }

    @Override
    public void query() {

        System.out.println("执行了查找方法...");
    }
}

4.Service层业务实现类

文件路径:com.dzj.service.UserService.java

package com.dzj.service;

import com.dzj.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    UserDaoImpl userDao;

    public void add(){
        userDao.add();
    }
    public void update(){
        userDao.update();
    }
    public void delete(){
        userDao.delete();
    }
    public void query(){
        userDao.query();
    }
}

5.Controller层接口控制类

文件路径:com.dzj.controller.UserController.java

package com.dzj.controller;

import com.dzj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ResponseBody
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/test")
    public String userTest(){

        userService.add();
        return "chenggongle...";
    }
}

6.编写业务类增强类,加入一个日志文件记录

package com.dzj.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Component
@Aspect
public class AdviceMethod {

    private static final Logger log = LoggerFactory.getLogger(AdviceMethod.class);

    @Pointcut("execution(public * com.dzj.service.UserService.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void before(JoinPoint joinPoint){

        //这个RequestContextHolder是Springmvc提供来获得请求的东西
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();

        // 记录下请求内容
        log.info("################URL : " + request.getRequestURL().toString());//获取请求的地址
        log.info("################HTTP_METHOD : " + request.getMethod());//获取请求的方法
        log.info("################IP : " + request.getRemoteAddr());
        log.info("################THE ARGS OF THE CONTROLLER : " + Arrays.toString(joinPoint.getArgs()));

        /**
         * getSignature().getDeclaringTypeName()   是获取包+类名的
         * joinPoint.getSignature.getName()  获取了方法名
         * joinPoint.getTarget() 返回的是需要加强的目标类的对象
         * joinPoint.getThis())  返回的是经过加强后的代理类的对象
         */
        log.info("################CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("################TARGET: " + joinPoint.getTarget());
        log.info("################THIS: " + joinPoint.getThis());
        System.out.println("方法执行之前...");
    }

    @After("webLog()")
    public void after(){
        System.out.println("方法执行之后...");
    }
}

7.运行测试,查看结果

启动主启动器类,在浏览器中输入http://localhost:8080/test,查看控制台输出信息
image

搞定,结束...

posted @ 2021-12-27 10:43  小公羊  阅读(173)  评论(0编辑  收藏  举报