Reputation: 91
I want to use log4j for java and sql. i want to print the java and sql logs without using "logger.debug("log4j logger")" in my class.
Below are the class and log4j properties used
package com.log4j;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class LogTest {
public static void main(String[] args) throws Exception{
final Logger logger = Logger.getLogger(LogTest.class);
PropertyConfigurator.configure("log4j.properties");
try {
Class.forName("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection("XXX", "YYY", "ZZZ");
String inserQuery = "insert into table1 (name,id) values (?,?)";
PreparedStatement prestat = conn.prepareStatement(inserQuery);
prestat.setString(1, "Test");
prestat.setString(2, "2");
prestat.executeUpdate();
}
catch (Exception ex)
{
System.out.println("Exception: " + ex.getMessage() + "");
}
}
}
Below is the log4j properties
log4j.rootLogger=DEBUG,CA
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
Please advise.
Any help will be appreciated
Thanks
Upvotes: 1
Views: 11314
Reputation: 42030
If you want to print the SQL sent to the database, you might want to use log4jdbc-log4j2. This acts as a proxy:
If you use log4j.jar
, you will require add slf4j-api.jar
and slf4j-log4j12.jar
.
Notes
* Images were obtained from JPA - Tracer les requêtes SQL avec Log4jdbc
Upvotes: 0
Reputation: 1069
Its like u created a variable which is never used then why create it, it would be better if you use
logger.error("Exception: " + ex.getMessage() + "");
instead of
System.out.println("Exception: " + ex.getMessage() + "");
Upvotes: 3
Reputation: 617
If java.sql has a logger interface it will probably be java.util.logging rather than LOG4J or SLF4J. I've looked at a few of the java.sql.* classes and it looks as if they have no logging at all. Your scheme would have worked had any of these classes used 4J logging but they don't so you'll just have to put the logging in your code.
Upvotes: 1