5

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.

5
  • 1
    which object you are trying to print? Seems like the class you are trying to print hasn't overridden toString(). Commented Jan 3, 2016 at 14:02
  • I'm not trying to print Any object. I just want to show the name of the Connection object which I have opened or closed. Commented Jan 3, 2016 at 14:03
  • an you post the code.. Commented Jan 3, 2016 at 14:05
  • 1
    You are trying to print an object: the Connection. Connection is an object. But a Connection doesn't have a name. Commented Jan 3, 2016 at 14:07
  • @JBNizet added Code snippets if that helps Commented Jan 3, 2016 at 14:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I was also planning for this aproach and then I read this document eclipsesource.com/blogs/2012/09/04/… And as per this source hashCode doesnt have to be unique for every object. That's where I had to lookout for other options.
@RajaAnbazhagan the chances of two hashCode()s for two Connections that are open at the same time being the same is next to zero. If you want to go overboard and make it 100% unique, do something like hashCode() + '-' + System.nanoTime(). I am able to use hashCode() as a unique id just fine when doing enterprise scale jdbc debugging in logs
Finally decided to go with the hexString of hashcode approach.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.