Red Hat Web Application Framework 6.1 Manuale Utente

Pagina di 230
44
Chapter 7. Developing with WAF
greater than or equal to the current level of the logger. For example, if you set the
foo.bar.baz
logger’s level to
warn
, it will only log message whose level is
warn
,
error
, or
fatal.
By
setting the level for the
foo.bar
logger, you are automatically setting it for
foo.bar.baz
and
foo.bar.quux,
unless overridden on a more specific level.
6. Miscellaneous other items such as filters
2
and flexible configuration.
The next sections examine some of these benefits in more detail.
7.5.2. Always log the Throwable
In general, if you catch an exception and decide not to rethrow it for whatever reason, you should log
it. In doing so, avoid the following anti-pattern:
try {
doSomething();
} catch (FooException ex) {
ex.printStackTrace();
s_log.warn("foo occurred: " + ex.getMessage());
}
Example 7-2. Exception logging anti-pattern
The
printStackTrace()
method should not be used, because its output goes to the standard error
device
System.err
rather than the devices managed by
Log4J.
The
getMessage()
method should not be used, because it does not include the stack trace. Stack
traces are invaluable for tracking down the source of error conditions.
The following pattern should be used instead.
try {
doSomething();
} catch (FooException ex) {
s_log.debug("foo occurred", ex); // or
s_log.info("foo occurred", ex);
// or
s_log.warn("foo occurred", ex);
// or
s_log.log(Level.WARN, "foo occurred", ex);
}
Example 7-3. Log the Throwable
Note that the various logging methods provided by the
Logger
3
class all take a Throwable parameter,
i.e. an Error or Exception. Given a throwable,
Log4J will print both the error message obtained via
getMessage()
and the stack trace.
However, be careful not to fall into this trap:
2. http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/spi/Filter.html
3. http://jakarta.apache.org/log4j/docs/api/org/apache/log4j/Logger.html