Our Simple Hibernate Application is a bit verbose. That’s probably okay for a web application because stdout actually ends up in a server log. But it’s a bit annoying in console application. Fortunately, Hibernate uses the Apache commons-logging abstraction layer and Hibernate logging is easily configured.
First, a quick aside on logging. Logging packages are a mechanism that allow a developer to add diagnostic messages to the code and specify the message level and destination at runtime. The design allows the developer to define a hierarchical logging structure in which each level inherits the properties of the level above it unless otherwise specified. Typically, the logging structure mirrors the package structure as that is both simple and effective. The JCL Users Guide is a good place to start for more information.
Apache commons-logging supports the log4j, JDK 1.4, and JCL SimpleLog Logging packages. We’ll use log4j because I’m already familiar with it and the Hibernate distribution includes a sample log4j.properties file.
Here are the required changes to our build.xml file (shown in bold). First, there is a new property that locates the log4j jar file. And second, the log4j jar file is added to the execution classpath.
And here is the log4j.properties file from my hibernate distribution.
- The first block of parameters define an output channel identified as stdout. This channel directs messages to the standard output.
- The second block of parameters define an output channel identified as file. This channel directs messages to the hibernate.log file.
- The rootLogger assignment defines the default behavior as directing messages at or more severe than the warn level to the stdout channel.
- And the remaining assignments change the output levels to info for the respective packages.
The easiest solution is to simply uncomment the lines defining the file channel and redefine the rootLogger to use the file channel. This will direct the log output to the hibernate.log file.
But here’s another option. We’ll create two properties files, one that directs the output to hibernate.log and another that directs the output to both System.out and hibernate.log. Then we’ll use the condition task and the java sysproperty task to specify the desired configuration file based upon the value of the TALK property.
Now we can specify via the command line whether to view the logging messages on System.out or not.
Our application still persists keyword objects without regard for existing keyword objects, but at least it does so quietly. If you’re following along, then here is the source for our Simple Hibernate application with log4j. We’ll fix the persistence problem next.
Disclaimer: I don’t claim to be an expert on hibernate. Please send comments and corrections.