• log4j 日志输出数据库


    一:添加依赖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信息");
        }
    }
  • 相关阅读:
    Java基础转换流InputStreamReader/OutputStreamWriter
    Java基础网络编程ServerClient通信(3)
    Java基础IO读取properties配置文件
    Java基础修改Properties配置文件
    Java基础网络编程ServerClient通信(1)
    Java基础BufferedInputStream和BufferedOutputStream拷贝文件
    Java基础BufferedWriter
    Java基础ObjectOutputStream和ObjectInputStream细节
    Java基础ObjectOutputStream、ObjectInputStream
    Java基础网络编程ServerClient通信(2)
  • 原文地址:https://www.cnblogs.com/zhanchaohan/p/14685755.html
Copyright © 2020-2023  润新知