devxlogo

Using the Logger to Trace JDBC Driver Managers and Drivers

Using the Logger to Trace JDBC Driver Managers and Drivers

Both JDBC drivers and the DriverManager use the PrintWriter for logging/tracing. Using java.util.Logger as your logging/tracing tool allows you to take advantage of the Logging framework.

Create an adapter class to redirect the log messages to java.util.Logging.

// Adapter class to redirect the logging/tracing statements from the // PrintWriter to the Logger.public class JDBCLogWriter extends Writer{    private final Logger myLogger;    private final Level myLogLevel;    public JDBCLogWriter(Logger logger)    {        this(logger, Level.INFO);    }    // Initialize the log writer    public JDBCLogWriter(Logger logger, Level level)    {        myLogger = logger;        myLogLevel = level;    }    // Redirect the log to the logger.    @Override    public void write(char[] cbuf, int off, int len) throws IOException    {        myLogger.log(myLogLevel, new String(cbuf, off, len));    }    @Override    public void flush() throws IOException    {    }    @Override    public void close() throws IOException    {    }    public static void main(String[] args) throws Exception    {        // Set the log writer by using the JDBCLogWriter        DriverManager.setLogWriter(new PrintWriter(new JDBCLogWriter(            Logger.getLogger("database"))));        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");    }}

devx-admin

Share the Post: