1、在MySQL中的Test数据库里建一张名日志表。脚本如下。
/* SQLyog Enterprise - MySQL GUI v6.03 Host - 5.0.83-community-nt : Database - test ********************************************************************* Server version : 5.0.83-community-nt */
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
create database if not exists `test`;
USE `test`;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*Table structure for table `systemlog` */
DROP TABLE IF EXISTS `systemlog`;
CREATE TABLE `systemlog` ( `username` varchar(16) default NULL, `classname` varchar(128) default NULL, `createdate` datetime default NULL, `id` int(11) NOT NULL auto_increment, `content` varchar(1000) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
/*Data for the table `systemlog` */
表结构如下图
2、Log4j日志属性文件配置如下:
log4j.logger.SYSTEM = DEBUG,JDBC
#JDBC configure
log4j.appender.JDBC.Threshold=DEBUG
log4j.appender.JDBC=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.JDBC.driver=com.mysql.jdbc.Driver
log4j.appender.JDBC.URL=jdbc:mysql://localhost:3306/test
log4j.appender.JDBC.user=root
log4j.appender.JDBC.password=3619379
log4j.appender.JDBC.layout=org.apache.log4j.PatternLayout
log4j.appender.JDBC.sql=INSERT INTO systemlog(username,createdate,classname,content)VALUES('%X{username}','%d{yyyy-MM-dd HH:mm:ss}','%p','%m')
3、日志工具类源码如下:
package test;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
publicclassLogUtil{
privatestaticLogger logger =Logger.getLogger("SYSTEM");
/**
* 崩溃级别
* @param username
* @param message
*/
publicstaticvoid fatal(String username,String message){
MDC.put("username", username);
logger.fatal(message);
}
/**
* 错误级别
* @param username
* @param message
*/
publicstaticvoid error(String username,String message){
MDC.put("username", username);
logger.error(message);
}
/**
* 消息级别
* @param username
* @param message
*/
publicstaticvoid info(String username,String message){
MDC.put("username", username);
logger.info(message);
}
/**
* 警告级别
* @param username
* @param message
*/
publicstaticvoid warn(String username,String message){
MDC.put("username", username);
logger.warn(message);
}
/**
* 调试级别
* @param username
* @param message
*/
publicstaticvoid debug(String username,String message){
MDC.put("username", username);
logger.debug(message);
}
}
4、客户端调用源码如下:
package test;
publicclassTestLog{
/**
* @param args
*/
publicstaticvoid main(String[] args){
LogUtil.info("张三","看看是否在TestLog中写入了日志");
}
}
最后运行TestLog,结果如下图所示: