We use Jakarta
Commons Logging version 1.0 as logging interface. It must be used
for any trace/debug/error output, directly printing to System.err or
System.out or the use of Exception.printStackTrace() are not allowed in
the server code. The logging interface allows to filter and process
logging output in many ways that are not possible if output is directly
written to the console. This is important for a system that is designed
to run 24 hours a day under heavy use. An exception is e.g. unit test
code that will not run in the server later.
The Commons Logging component provides an easy to use interface. We
recommend to acquire an instance to the log interface for every class
separately. That allows later to filter output based on the class and
package names. Your code would look like this:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
class MyServerClass {
private final Log log = LogFactory.getLog(this.getClass());
public void run() {
log.trace("run entered");
...
log.trace("run left");
}
}
If you need access to the log from a static method, this would work for you:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
class MyServerClass {
static private final Log log =
LogFactory.getLog(MyServerClass.class);
public static void main() {
log.trace("main entered");
...
log.trace("main left");
}
}
The Log interface provides six logging levels that have
corresponding methods. For example, for the trace logging
level, the Log interface provides the methods trace(java.lang.Object
message) and trace(java.lang.Object message,
java.lang.Throwable t). If you want to log an exception, always
use the second form and pass the exception to the t
parameter. The message parameter should usually just be a
plain string. Please don't use any fancy formatting, method, package, or
thread names in the message. The Commons Logging allows the user to
configure the final format of the log messages and inject things like
the thread name.
If creating the log message becomes an expensive operation, it is
recommended to first check if the log level is currently enabled. Your
code would look like this:
if (log.isDebugEnabled()) {
... create a message ...
log.debug(message);
}
If you use a construct like the above, please make sure that you are
not accidentally creating any side effects, i.e. don't set any variables
or invoke methods that change state. Otherwise you are likely to create
very difficult to find bugs that depend on the selected log level at
runtime.
Finally, here are some recommendations on what log level to choose: