一:添加依赖jar
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency>
二:配置log4j
log4j.rootLogger = stdout,jdbc log4j.appender.jdbc=org.apache.log4j.jdbc.JDBCAppender log4j.appender.jdbc.driver=com.mysql.jdbc.Driver log4j.appender.jdbc.URL=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=true&serverTimezone=UTC log4j.appender.jdbc.user=root log4j.appender.jdbc.password= log4j.appender.jdbc.sql=insert into log_info(level,category,thread,time,location,note) values('%p','%c','%t','%d{yyyy-MM-dd HH:mm:ss:SSS}','%l','%m')
三:创建数据库表结构
@Test public void jdbcCreateTable() throws Exception { Connection connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=true&serverTimezone=UTC", "root", ""); Class.forName("com.mysql.cj.jdbc.Driver"); connection.createStatement().execute("CREATE TABLE `log_info` ( " + " `Id` int(11) NOT NULL AUTO_INCREMENT, " + " `level` varchar(255) NOT NULL DEFAULT '' COMMENT '优先级', " + " `category` varchar(255) NOT NULL DEFAULT '' COMMENT '类目', " + " `thread` varchar(255) NOT NULL DEFAULT '' COMMENT '进程', " + " `time` varchar(30) NOT NULL DEFAULT '' COMMENT '时间', " + " `location` varchar(255) NOT NULL DEFAULT '' COMMENT '位置', " + " `note` text COMMENT '日志信息', " + " PRIMARY KEY (`Id`) " + ")"); }
四:添加测试代码
/*** * * @author zhanchaohan * */ public class PrintTest { private static Logger logger = Logger.getLogger(PrintTest.class); public static void main(String[] args) throws Exception { PropertyConfigurator.configure(PrintTest.class.getResource("/log4j.properties")); logger.info("普通Info信息"); logger.debug("调试debug信息"); logger.error("报错error信息"); logger.warn("警告warn信息"); logger.fatal("严重错误fatal信息"); } }