# log4j写入数据库
### 前言
-----------------------------
log4j是写入日志到控制台和文件很常见,但是写入到数据库不多见.
做性能测试写入到数据库,统计方便些.
### POM
-----------------------------
```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yctxkj</groupId>
<artifactId>logtest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>logtest</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- junit 4.11 的依赖 -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3.RC2</version>
</dependency>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<defaultGoal>compile</defaultGoal>
<plugins>
<!-- jdk版本 -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.4</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
### 配置文件
-----------------------------
```
log4j.rootLogger=INFO,console,file,database
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[KMS] %d{yyyy-MM-dd HH\:mm\:ss.SSS} [%5p] (%F\:%L) - %m%n
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern='.'yyyy-MM-dd
log4j.appender.file.File=/data/logs/logtest.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss.SSS} [%5p] (%F\:%L) - %m%n
log4j.logger.freemarker=FATAL
### \u628a\u65e5\u5fd7\u4fe1\u606f\u5199\u5165\u5230\u6570\u636e\u5e93###
log4j.appender.database=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.database.driver=com.mysql.jdbc.Driver
log4j.appender.database.URL=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
log4j.appender.database.user=root
log4j.appender.database.password=123456
log4j.appender.database.sql=insert into log (class,lineno,method,createtime,level,message) VALUES ('%F','%L','%M','%d{yyyy-MM-dd hh:mm:ss.SSS}','%p','%m')
log4j.appender.database.layout=org.apache.log4j.PatternLayout
```
### 代码
-----------------------------
```
package com.yctxkj.logtest;
import org.apache.log4j.Logger;
/**
* Hello world!
*
*/
public class App
{
private static Logger logger = Logger.getLogger(App.class);
public static void main( String[] args )
{
System.out.println( "Hello World!" );
logger.info("我很困啊啊,想睡觉");
logger.warn("this is warning message");
}
}
```
### 数据库脚本
-----------------------------
```
-- ----------------------------
-- Table structure for log
-- ----------------------------
DROP TABLE IF EXISTS `log`;
CREATE TABLE `log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`level` varchar(8) NOT NULL,
`class` varchar(45) DEFAULT NULL,
`lineno` int(11) DEFAULT NULL,
`message` text,
`method` varchar(45) DEFAULT NULL,
`createtime` datetime(3) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COMMENT='log4j日志表';
```
### 效果截图
-----------------------------
- ![截图]()
### 日志加入自定义字段
-----------------------------
在使用log4j日志的时候,有时需要在日志中加入自定义字段信息,
例如在日志中加入登录用户的信息等,这时就可以使用org.apache.log4j.MDC来实现该功能:
1.在Action的方法中,直接使用
```
MDC.put("username",getUserInfo().getName()); //getUserInfo()获取登录用户信息
```
2.在log4j的配置文件中,
```
%d{yyyy/MM/dd HH:mm:ss.sss} [%X{username}] [%-5p] %c - %m%n
```
3.日志文件结果:
`2013/11/29 18:00:25.025 [test] [ERROR] com.test.TestAction //红色test即为加入的用户信息`