Activate logging in Hibernate

Logging is extremely well done in hibernate and can be quite useful in case of problems.

Hibernate uses slf4j to perform logging. ¬†Slf4j is just a facade for logging and uses an underlying system to actually perform logging. One can use whatever logging system wishes, it basically depends on personal preferences and whatever you’re more familiar configuring.

For this example I choose log4j 1.2, but log4j 2, logback etc are also possible.

In order to enable logging through log4j1.2 you should have the following dependency in your pom.xml:

Above I use version 1.7.25 which is the latest at this time, but older versions should work as well.

Log4j is configured through a file that you should put in your resources folder (that can be under either src/main or test/main depending if you wish to use it for production logging or only in a test setting).

Here’s a sample of a that activates sets the rootLogger to INFO level only, but activates the DEBUG level for hibernate. Warning! it’s not exactly the TRACE level, but it can still yield a lot of output.

SecureRandom gotcha

If you need a random number you are usually advised to use SecureRandom because it gives a cryptographically secure random number.

Typical way of calling SecureRandom would be:

From a random generator seeding perspective this is also the correct way. You might be tempted to call the setSeed in order to seed with some long that you provide. Resist that temptation unless you can prove that the seed obeys the constraints of your application (like that it is different between different instantiations and invocations of SecureRandom). And no, seeding with the System.currentTimeMillis() will not work: multiple threads can get the same value.

Here’s an excerpt from the setSeed documentation:

The interesting part here is that it says that the seed “supplements” the internal seed. This is not what I found. The given seed will completely replace the internal seed. This means that when seeded the same way two SecureRandom will return the same value. Probably not what you would expect.