MySQL Connector/J 8.0 Developer Guide

Chapter 12 Using Logging Frameworks with SLF4J

Besides its default logger com.mysql.cj.log.StandardLogger, which logs to stderr, Connector/J supports the SLF4J logging facade, allowing end users of applications using Connector/J to plug in logging frameworks of their own choices at deployment time. Popular logging frameworks such as java.util.logging, logback, and log4j are supported by SLF4J. Follow these requirements to use a logging framework with SLF4J and Connector/J:

The log category name used by Connector/J with SLF4J is MySQL. See the SLF4J user manual for more details about using SLF4J, including discussions on Maven dependency and bindings. Here is a sample code for using SLF4J with Connector/J:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.cj.jdbc.JdbcConnection;
import com.mysql.cj.log.Log;

public class JDBCDemo {
  public static void main(String[] args) {
    Connection conn = null;
    Statement statement = null;
    ResultSet resultSet = null;
    Log logger = null;
  try {
     // Database parameters
     String url = "jdbc:mysql://";
     String user = "user";
     String password = "password";
     // create a connection to the database
     conn = DriverManager.getConnection(url, user, password);
     logger = ((JdbcConnection)conn).getSession().getLog();
  catch (SQLException e) {

  try {
     statement = conn.createStatement();
     resultSet = statement.executeQuery("SELECT * FROM pets.dogs");
       System.out.printf("%d\t%s\t%s\t %4$ty.%4$tm.%4$td \n",
  catch(SQLException e) {
     logger.logWarn("Warning: Select failed!");



If you want to use, for example, Log4j 1.2.17 as your logging framework when running this program, use its binding to SLF4J: put slf4j-api-1.7.28.jar (SLF4J API module), slf4j-log4j12-1.7.28.jar (SLF4J's binding for Log4J 1.2), and log4j-1.2.17.jar (Log4J library) in your Java classpath.

Here is output of the program when the SELECT statement failed:

[2019-09-05 12:06:19,624] WARN     0[main] - WARN MySQL - Warning: Select failed!