-2

I have created the below JDBC connection and it is working fine now with the below code and I am using log4j, in case of any JDBC connection failure I wanted to log that in log file rather to show in console

public class projectDaoJdbcImpl implements projectDao {
static Logger logger = Logger.getLogger(projectDaoJdbcImpl.class);


@Override
public boolean updateproject(updateentity projectObj) throws Exception {
    FileInputStream fis = new FileInputStream("C:\\Users\\kdhandap\\database.properties");
    Properties props = new Properties();
    props.load(fis);
    String JDBC_DRIVER = props.getProperty("Driver");
    String USER = props.getProperty("Username");
    String PASS = props.getProperty("Password");
    String url = "jdbc:mysql://" + projectObj.getServerName() + ":3306/tablename";
    boolean result = false;
    Connection conn = null;
    PreparedStatement stmt = null;
    String sql = "UPDATE table SET columnname='" + projectObj.getFlagStatus()
            + "' WHERE projectID IN (" + projectObj.projectId() + ")";

    try {
        Class.forName(JDBC_DRIVER);
        conn = DriverManager.getConnection(url, USER, PASS);
        stmt = conn.prepareStatement(sql);
        if (stmt.executeUpdate() != 0) {
            result = true;
        }

    }

    catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException se) {
        se.printStackTrace();
    }
    finally{
        stmt.close();
        conn.close();
    }
    return result;

}

Trying to have a logger.warn status and to capture in log file and not sure where to handle it

Vlad Bochenin
  • 3,007
  • 1
  • 20
  • 33
Keerthisairam
  • 81
  • 3
  • 10
  • handling in SQL Exception should do it..also if u want to handle other exceptions, try removing "throws Exception" from method declaration – Nabarun Dey Jan 13 '17 at 12:06
  • I'm not sure I understand the problem. You have a logger. You need to call its warn() method, instead of using e.printStackTrace(). What's the concrete problem? – JB Nizet Jan 13 '17 at 12:06
  • i wanted to capture the output of e.printStackTrace(). in my log file – Keerthisairam Jan 13 '17 at 12:49

1 Answers1

2

You can do like this inside your catch:

logger.warn("YourMessage",e);

Which will log and print stracktrace inside your log file.

From JavaDoc:

Logs a CharSequence at the WARN level including the stack trace of the Throwable t passed as parameter.

Same thing you can do this for other levels based on your requirements.

Pradeep Simha
  • 17,683
  • 18
  • 56
  • 107