Using java.util.logging with JDBC drivers for the HyperSQL Database Engine

﹥>﹥吖頭↗ 提交于 2019-12-13 13:17:41

问题


After searching for the answers to my questions Implementing logging in a Java application and Using the java.util.logging package in a Swing application about the java.util.logging package, I have tracked down the problem and want to share my solution here. I am posting this as a new question to (hopefully) give a concise statement of the actual problem (which is not entirely clear in my previous questions because I was asking the wrong question) as well as to give a (hopefully) clear answer.

The following code illustrates the problem:

package jdbcloggingsscce;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class JDBCLoggingSSCCE {
    public static void main(String[] args) throws IOException, SQLException {
        JDBCLoggingSSCCE.initLogger();
        Logger logger = Logger.getLogger(JDBCLoggingSSCCE.class.getName());
        logger.log(Level.INFO, "Starting JDBCLoggingSSCCE");

        Connection conn = DriverManager.getConnection(DB_URL);
        logger.log(Level.INFO, "JDBC Connection created");
    }

    private static void initLogger() throws IOException {
        Handler handler = new FileHandler(JDBCLoggingSSCCE.LOG_FILE_NAME);
        handler.setFormatter(new SimpleFormatter());

        Logger logger = Logger.getLogger("");
        logger.setLevel(Level.ALL);
        logger.addHandler(handler);
    }
    private static final String LOG_FILE_NAME = "jdbcloggingsscce.log";
    private static final String DB_URL = "jdbc:hsqldb:file:db/jdbcloggingsscce.db";
}

This example uses the JDBC drivers for the HyperSQL Database Engine (HSQLDB). The problem is that the first logging message ("Starting JDBCLoggingSSCCE") is logged, but the second message ("JDBC Connection created") is not.


回答1:


The solution is to set a system property called "hsqldb.reconfig_logging" to false. One way to set this property is to add the following line of code to the end of the initLogger() method:

System.setProperty("hsqldb.reconfig_logging", "false");

I believe that placement isn't entirely crucial as long as it is before the call to DriverManager.getConnection(DB_URL). Setting this "hsqldb.reconfig_logging" property tells the HSQLDB JDBC driver to not reconfigure Loggers from the java.util.logging package. The result is logging in the rest of the application continues as desired. Of course, HSQLDB also includes logging messages itself, but dealing with those is for another Q&A.



来源:https://stackoverflow.com/questions/12353990/using-java-util-logging-with-jdbc-drivers-for-the-hypersql-database-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!