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");    }}
See also  Redefining Energy Management: Advanced Solutions for Modern Buildings
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist