Logging Frameworks With Slf4J: Com - Mysql.Cj - Log.Standardlogger Stderr
Logging Frameworks With Slf4J: Com - Mysql.Cj - Log.Standardlogger Stderr
o Install the logging framework of your choice on your system and add it to the
Java classpath.
o Configure the logging framework of your choice. This often consists of setting up
appenders or handlers for log messages using a configuration file; see your logging
framework's documentation for details.
o When connecting the application to the MySQL Server, set the Connector/J
connection property logger to Slf4JLogger.
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;
try {
// Database parameters
String url = "jdbc:mysql://myexample.com:3306/pets?
logger=Slf4JLogger&explainSlowQueries=true";
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) {
System.err.println(e.getMessage());
System.exit(1);
}
try {
statement = conn.createStatement();
resultSet = statement.executeQuery("SELECT * FROM pets.dogs");
while(resultSet.next()){
System.out.printf("%d\t%s\t%s\t %4$ty.%4$tm.%4$td \n",
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getString(3),
resultSet.getDate(4));
}
}
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: