使用Java代码实现log4j2日志写入MySQL数据库
时间: 2023-04-06 20:04:41 浏览: 146
如何借助log4j把日志写入数据库中
3星 · 编辑精心推荐
可以的,以下是Java代码实现log4j2日志写入MySQL数据库的示例:
1. 首先,需要在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
```
2. 在log4j2.xml文件中配置MySQL数据库的Appender:
```
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<JDBC name="databaseAppender" tableName="logs">
<ConnectionFactory class="com.mysql.cj.jdbc.MysqlDataSource">
<param name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC"/>
<param name="user" value="root"/>
<param name="password" value="123456"/>
</ConnectionFactory>
<Column name="timestamp" isEventTimestamp="true"/>
<Column name="level" pattern="%level"/>
<Column name="logger" pattern="%logger"/>
<Column name="message" pattern="%message"/>
</JDBC>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="databaseAppender"/>
</Root>
</Loggers>
</Configuration>
```
3. 在Java代码中使用log4j2记录日志:
```
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) {
logger.info("Hello, log4j2!");
}
}
```
4. 最后,在MySQL数据库中创建表logs:
```
CREATE TABLE logs (
id INT NOT NULL AUTO_INCREMENT,
timestamp TIMESTAMP NOT NULL,
level VARCHAR(10) NOT NULL,
logger VARCHAR(100) NOT NULL,
message TEXT NOT NULL,
PRIMARY KEY (id)
);
```
这样,log4j2就会将日志记录到MySQL数据库中的logs表中。
阅读全文