Spring-boot2使用log4j2中JDBCAppender将日志写入数据库(MySql/HikariCP/yml)
如何将log4j2集成到Spring-boot
1 导入依赖
Spring-boot2 中Starters包含log4j2,所以进入log4j2只要引入以下依赖性进入pom.xml
<!--日志管理-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
但是,Spring-boot默认是使用Logback来进行日志管理,所以你需要将自带的log包从Spring-boot中去除。
<!--去掉web中自带的logging-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
如果你在之后遇到了以下 多重绑定错误:
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/E:/maven-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:/E:/maven-repository/org/apache/logging/log4j/log4j-slf4j-impl/2.11.2/log4j-slf4j-impl-2.11.2.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]
你需要检查你其他依赖中是否也引入了日志包而造成多重绑定,常见的是spring-boot-starter-thymeleaf和Zookeeper两个依赖包。你可以也将其中的日志包去除掉,这里以thymeleaf为例:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<!--排除这个默认日志记录依赖-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
2 配置log4j2
所有配置都按照log4j2官方文档-配置进行配置。
官方提供了4中配置方式,分别是配置文件、ConfigurationFactory、使用APIs和调用内部日志类方法。
以下是官方说明:
Configuration of Log4j 2 can be accomplished in 1 of 4 ways:
1.Through a configuration file written in XML, JSON, YAML, or properties format.
2.Programmatically, by creating a ConfigurationFactory and Configuration implementation.
3.Programmatically, by calling the APIs exposed in the Configuration interface to add components to the default configuration.
4.Programmatically, by calling methods on the internal Logger class.
2.1配置log4j2.xml
本文采用YAML格式配置,其余方式可以自行去官方文档查看。我这里采用YAML配置的原因是,这次Spring-boot的配置文件采用YAML进行配置,觉得格式清晰,操作方便。
我们在application.yml或者application.properties同级目录下,创建配置文件log4j2.yml,代码如下:
Configuration:
status: warn
Properties: # 定义全局变量
Property: # 缺省配置(用于开发环境)。其他环境需要在VM参数中指定,如下:
#测试:-Dlog.level.console=warn -Dlog.level.sdk=trace
#生产:-Dlog.level.console=warn -Dlog.level.sdk=info
- name: log.level.console
value: trace
- name: log.level.sdk.mapper
value: debug
- name: log.path
value: E:/logs
- name: project.name
value: sdk_manage
Appenders:
Console: #输出到控制台
name: CONSOLE
target: SYSTEM_OUT
Thres

本文详细介绍了如何在Spring-boot2项目中集成log4j2,通过配置log4j2.yml文件和使用HikariCP连接池,实现日志数据写入MySql数据库。步骤包括导入相关依赖,配置log4j2,设置Hikari连接池,以及创建JDBCAppender。同时,文章提供了配置文件示例和数据库表创建脚本。
最低0.47元/天 解锁文章
4183

被折叠的 条评论
为什么被折叠?



