I have a simple webapp that acquires connection from tomcat JDBC datasource. To track the connection usage, I'm planning to implement logging while opening and closing connection. The logging supposed to print something like this.
20151230143623.947[Thread-3] INFO [DataSourceManager:19] Opened connection identified by id : BlahBlahBlah1
20151230143623.947[Thread-3] INFO [DataSourceManager:19] Closed connection identified by id : BlahBlahBlah1
My open and close methods are like this.
Connection openConnection(String JNDILookupName) throws Exception {
Connection connection = DataSourceManager.getConnection(JNDILookupName);
logDBOperation("Opened", connection.toString());
return connection;
}
Connection closeConnection(String JNDILookupName) throws Exception {
connection.close();
logDBOperation("Closed", connection.toString());
}
void logDBOperation(String operation, String connecitonName){
logger.info(operation+" connection identified by id : "+connectionName);
}
Here I'm using connection.toString()
as the Connection's unique name in the Logs. But I want to know if there is any better way to do this.
Just use the default toString()
implementation on the Object
superclass.
It already does this for you:
getClass().getName() + '@' + Integer.toHexString(hashCode())
The toHexString(hashCode())
will give you the unique id right there. And this is a guarantee by the JVM that it will be a unique value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With