SpringBoot+Druid+Log4j2配置总结

前言

在springboot配置Druid及配置Log4j2日志时,先去官方文档了解,结果还是意料之中还是有一些坑,更多的是版本问题导致的,网上找了许多,但是准确定位到springboot2.0.3的版本相关的资料太少了,更多的是零零散散的,不过互补一下后整个配置流程还是没什么问题的,这里总结下整个配置流程及一些坑。(推荐首先了解相关官方文档,再针对于某些不同版本或配置导致的问题去查看相关博客等,更容易了解整个流程及节省时间)

正文后面列举了一些踩坑问题及处理方法。

所用版本:

  1. SpringBoot 2.0.3
  2. Druid 1.1.10
  3. Log4j2 2.10.0

正文

首先附Druid官方的文档,推荐先了解下。

Druid官方git文档:https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98

一、配置pom.xml


    org.springframework.boot
    spring-boot-starter-parent
    2.0.3.RELEASE
    


    org.springframework.boot
    spring-boot-starter
    
        
            org.springframework.boot
            spring-boot-starter-logging
        
    


    com.alibaba
    druid-spring-boot-starter
    1.1.10



    org.springframework.boot
    spring-boot-starter-log4j2

二、配置application.yml,Druid连接池的相关配置

spring:
  datasource:
      type: com.alibaba.druid.pool.DruidDataSource
      druid:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://192.168.123.180:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false
        username: root
        password: root
        # 配置初始化大小、最小、最大
        initial-size: 20
        min-idle: 1
        max-active: 50
        #配置获取连接等待超时的时间
        max-wait: 60000
        #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        time-between-eviction-runs-millis: 60000
        #配置一个连接在池中最小生存的时间,单位是毫秒
        min-evictable-idle-time-millis: 300000
        #测试连接
        validation-query: SELECT 'x'
        #申请连接的时候检测,建议配置为true,不影响性能,并且保证安全性
        test-while-idle: true
        #获取连接时执行检测,建议关闭,影响性能
        test-on-borrow: false
        #归还连接时执行检测,建议关闭,影响性能
        test-on-return: false
        #是否开启PSCache,PSCache对支持游标的数据库性能提升巨大,oracle建议开启,mysql下建议关闭
        pool-prepared-statements: false
        #开启poolPreparedStatements后生效
        max-pool-prepared-statement-per-connection-size: 20
        #配置扩展插件,常用的插件有=>stat:监控统计  log4j:日志  wall:防御sql注入
        filters: stat,wall,log4j2
        # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
        # Druid WebStatFilter配置
        web-stat-filter:
          enabled: true
          url-pattern: /*
          exclusions: '*.gif,*.png,*.jpg,*.html,*.js,*.css,*.ico,/druid/*'
        # Druid StatViewServlet配置
        stat-view-servlet:
          enabled: true
          url-pattern: /druid/*
          reset-enable: true
          login-username: admin
          login-password: admin
        # 配置日志输出
        filter:
          slf4j:
            enabled: true
            statement-create-after-log-enabled: false
            statement-close-after-log-enabled: false
            result-set-open-after-log-enabled: false
            result-set-close-after-log-enabled: false
logging:
  config: classpath:log4j2.xml

三、配置log4j2参数文件

log4j的参数配置有xml,yml,json多种配置方式,这里我们展示xml和yml的两种配置方式。

以下是相关的官方文档地址,推荐先了解一下

SpringBoot官网地址:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-configure-log4j-for-logging-yaml-or-json-config

Log4j2配置官网地址:https://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration

1. 采用xml配置,log4j2.xml



    

        
            
            
            
        

        
        
        
            
                
                
            
            
            
                
                
            
        

        
        
            
                
                
                
            
            
            
                
                
            
        

        
        
            
                
                
            
            
            
                
                
            
        

        
        
            
            
            
                
                
            
        

        
        
            
            
                
                
            
        
    

    
        
            
            
            
            
            
        

        
        
            
        
        
            
        

        
        
        
        
        
        
        
        
        
        
        
        
        
    

2. 采用yml配置,log4j2.yml

 采用yml配置,需要修改pom.xml,添加如下,否则控制台会报错,同时对应的application.yml需要将log4j2.xml改为log4j2.yml。


        
            com.fasterxml.jackson.dataformat
            jackson-dataformat-yaml
        
Configuration:
  status: OFF
  name: YAMLConfigTest
  properties:
    property:
      name: filename
      value: target/test-yaml.log
  thresholdFilter:
    level: debug
  appenders:
    #只接受程序中DEBUG级别的日志进行处理
    Console:
      name: Console
      target: SYSTEM_OUT
      ThresholdFilter:
        level: DEBUG
        onMatch: ACCEPT
        onMismatch: DENY
      PatternLayout:
        Pattern: "[%d{HH:mm:ss.SSS}] %-5level %class{36} %L %M - %msg%xEx%n"
    #处理DEBUG级别的日志,并把该日志放到logs/debug.log文件中
    RollingFile:
      #打印出DEBUG级别日志,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档
      -
        name: RollingFileDebug
        fileName: ./logs/debug.log
        filePattern: "logs/$${date:yyyy-MM}/debug-%d{yyyy-MM-dd}-%i.log.gz"
        PatternLayout:
          Pattern: "[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"
        Filters:
          ThresholdFilter:
            -
              level: DEBUG
            -
              level: INFO
              onMatch: DENY
              onMismatch: NEUTRAL
        Policies:
          SizeBasedTriggeringPolicy:
            size: 512MB
      #处理INFO级别的日志,并把该日志放到logs/info.log文件中
      -
        name: RollingFileInfo
        fileName: ./logs/info.log
        filePattern: "logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz"
        PatternLayout:
          Pattern: "[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"
        Filters:
          #只接受INFO级别的日志,其余的全部拒绝处理
          ThresholdFilter:
            -
              level: INFO
            -
              level: WARN
              onMatch: DENY
              onMismatch: NEUTRAL
        Policies:
          SizeBasedTriggeringPolicy:
            size: 512MB
      #处理WARN级别的日志,并把该日志放到logs/warn.log文件中
      -
        name: RollingFileWarn
        fileName: ./logs/warn.log
        filePattern: "logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log.gz"
        PatternLayout:
          Pattern: "[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"
        Filters:
          ThresholdFilter:
            -
              level: WARN
            -
              level: ERROR
              onMatch: DENY
              onMismatch: NEUTRAL
        Policies:
          SizeBasedTriggeringPolicy:
            size: 512MB
      #处理error级别的日志,并把该日志放到logs/error.log文件中
      -
        name: RollingFileError
        fileName: ./logs/error.log
        filePattern: "logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz"
        PatternLayout:
          Pattern: "[%d{yyyy-MM-dd HH:mm:ss}] %-5level %class{36} %L %M - %msg%xEx%n"
        ThresholdFilter:
          level: ERROR
        Policies:
          SizeBasedTriggeringPolicy:
            size: 512MB
      #druid的日志记录追加器
      -
        name: druidSqlRollingFile
        fileName: ./logs/druid-sql.log
        filePattern: "logs/$${date:yyyy-MM}/api-%d{yyyy-MM-dd}-%i.log.gz"
        PatternLayout:
          Pattern: "[%d{yyyy-MM-dd HH:mm:ss}] %-5level %L %M - %msg%xEx%n"
        Policies:
          SizeBasedTriggeringPolicy:
            size: 512MB
  loggers:
    logger:
      #记录druid-sql的记录
      name: druid.sql.Statement
      level: debug
      additivity: false
      appender-ref:
        ref: druidSqlRollingFile
    #log4j2 自带过滤日志
    Logger:
      -
        name: org.apache.catalina.startup.DigesterFactory
        level: error
      -
        name: org.apache.catalina.util.LifecycleBase
        level: error
      -
        name: org.apache.coyote.http11.Http11NioProtocol
        level: warn
      -
        name: org.apache.sshd.common.util.SecurityUtils
        level: warn
      -
        name: org.apache.tomcat.util.net.NioSelectorPool
        level: warn
      -
        name: org.crsh.plugin
        level: warn
      -
        name: org.crsh.ssh
        level: warn
      -
        name: org.eclipse.jetty.util.component.AbstractLifeCycle
        level: error
      -
        name: org.hibernate.validator.internal.util.Version
        level: warn
      -
        name: org.springframework.boot.actuate.autoconfigure.CrshAutoConfiguration
        level: warn
      -
        name: org.springframework.boot.actuate.endpoint.jmx
        level: warn
      -
        name: org.thymeleaf
        level: warn
    root:
      level: DEBUG
      appender-ref:
        -
          ref: Console
        -
          ref: RollingFileInfo
        -
          ref: RollingFileWarn
        -
          ref: RollingFileError
        -
          ref: RollingFileDebug

四、启动springboot,访问druid页面

正常springboot启动后,可以浏览器访问http://localhost:8080/druid/index.html,上文我已经配置了登录权限,需要登录才能查看

SpringBoot+Druid+Log4j2配置总结_第1张图片

输入用户名admin,密码admin之后可以查看到具体的信息如下

SpringBoot+Druid+Log4j2配置总结_第2张图片

 

附踩坑及解决方法

1、spring boot默认的是logback日志管理,配置log4j2之前需要移除logback相关包,官方文档的pom.xml配置是



	org.springframework.boot
	spring-boot-starter-web
	
		
			org.springframework.boot
			spring-boot-starter-logging
		
	

发现并不能完全移除logback,而导致控制会报如下错误

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/78794/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/78794/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.10.0/log4j-slf4j-impl-2.10.0.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
15:44:12.716 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
15:44:12.720 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/, /spring-boot/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter/target/classes/]
15:44:12.721 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/E:/IdeaProjects/qimiaochong/target/classes/]
Logging system failed to initialize using configuration from 'classpath:log4j2.yml'
java.lang.IllegalStateException: Could not initialize Logback logging from classpath:log4j2.yml

pom.xml改为如下即可


    org.springframework.boot
    spring-boot-starter
    
       
           org.springframework.boot
           spring-boot-starter-logging
       
    

 

以上有任何错误或者不够妥当的地方,欢迎及时指正,共同学习。

你可能感兴趣的:(SpringBoot)