欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring boot AOP统一日志管理

程序员文章站 2022-04-25 20:08:27
...

我们需要使用日志和aop管理,日志我们用log4j记录,我们需要在pom.xml里面引入log4j和aop

其中日志,因为spring boot starter里面的logging包依赖着log4j

我们需要去掉这个logging依赖,然后重新导入log4j。使用mvn denpendency:tree命令可以查看依赖树

导入log4j的时候要注意版本问题,pom.xml文件如果没有声明的话,以parent的版本为主,parent版本太高,log4j没有更新到那个版本,所以我们需要自己指定到Log4j的最新版本。查看log4j的最新版本可以浏览https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j

  <!--丢掉依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--重新导入log4j-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j</artifactId>
            <version>1.3.8.RELEASE</version>
        </dependency>

接着我们导入aop

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

log4j的使用还需要在resource下新建一个log4j.properties文件

里面写上配置信息

log4j.rootLogger =INFO,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c - %L]%m%n

log4j.appender.File=org.apache.log4j.RollingFileAppender
log4j.appender.File.File=C:/Users/Administrator/IdeaProjects/yorkmass/src/main/resources/log/info.log
log4j.appender.File.MaxFileSize=10MB

log4j.appender.File.Threshold=ALL
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c - %L]%m%n

导入完成之后,我们新建一个aspect包,然后在里面新建一个java类,写aop代码即可

切入点表达式相关问题参考https://www.cnblogs.com/myitnews/p/11553177.html

package com.yorkmass.demo.aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
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 javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

@Aspect
@Component //配置bean
public class WebLogAspect {
    private Logger logger=Logger.getLogger(getClass());

    //execution(<修饰符模式>?<返回类型模式><方法名模式>(<参数模式>)<异常模式>?)  除了返回类型模式、方法名模式和参数模式外,其它项都是可选的。
    //#匹配定义在com.yorkmass.demo.controller包或者子包里的任意public方法的执行:如下。第一个*表示返回类型为任意。com.yorkmass.demo.controller..*.*表示返回包或子包的任意方法名。最后(..)返回任意参数
    @Pointcut("execution(public * com.yorkmass.demo.controller..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        //接收到请求,记录请求内容
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        logger.info("-------------------requerst--------------------");
        logger.info("URL:"+request.getRequestURL().toString());
        logger.info("HTTP_METHOD:"+request.getMethod());
        logger.info("IP:"+request.getRemoteAddr());
        Enumeration<String> enu=request.getParameterNames();
        while (enu.hasMoreElements()){
            String name=(String)enu.nextElement();
            logger.info("name:"+name+"--value:"+request.getParameter(name));
        }
    }
    @AfterReturning(returning = "ret",pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable{
        logger.info("-------------response--------------");
        //处理完请求,应答
        logger.info("RESPONSE:"+ret);
    }


}

最后在app.java中(入口程序),添加扫描这个aspect包即可运行

package com.yorkmass.demo;

import com.yorkmass.demo.dbconfig.DBConfig1;
import com.yorkmass.demo.dbconfig.DBConfig2;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
//@ComponentScan(basePackages = {"com.yorkmass.demo.controller","com.yorkmass.demo.exception","com.yorkmass.demo.datasource","com.yorkmass.demo.test1.service","com.yorkmass.demo.test2.service"})
@ComponentScan(basePackages = {"com.yorkmass.demo.dbconfig","com.yorkmass.demo.datasource","com.yorkmass.demo.controller","com.yorkmass.demo.aspect","com.yorkmass.demo.exception","com.yorkmass.demo.test1.service","com.yorkmass.demo.test2.service"})
@EnableConfigurationProperties(value = {DBConfig1.class, DBConfig2.class})
//@MapperScan(basePackages ="com.yorkmass.demo.mapper")

public class App {
    public static void main(String[] args){
        SpringApplication.run(App.class,args);
    }
}