Red Hat Web Application Framework 6.1 Manuale Utente

Pagina di 230
Chapter 7. Developing with WAF
45
try {
doSomething();
} catch (FooException ex) {
s_log.debug(ex);
}
Example 7-4. Swallowed stack trace anti-pattern
There is no
debug(Throwable throwable)
method — there is only
debug(Object msg)
. Same
goes for warn, info, etc. The above statement is essentially equivalent to the following:
s_log.debug(String.valueOf(ex));
This is probably not the intended result.
What if you want to log the current stack trace? The easiest way to do this is to log a new
Throwable
:
s_log.debug("got here", new Throwable());
Example 7-5. Logging the current stack trace
A variation of this technique is to add a public
Throwable
field to a class.
public class Frob {
// add the following line temporarily
public final Throwable STACK = new Throwable();
}
Example 7-6. Tracking the origin of an object
Once this has been done, you can write code such as this:
class Foobar {
void doStuff(Frob frob) {
if ( !checksOutOK(frob) ) {
s_log.error("Got a sketchy frob", frob.STACK);
}
}
}
This allows you to figure the origin of the
frob
object at a distant point further down the execution
path.
7.5.3. Runtime logging level manipulation
Logging levels are usually configured at system startup via the configuration file. It is possible to
change the logger’s level at runtime. One way to do this is via the
Developer Support interfaces. (See
Section 7.3 Developer Support.) From the programmatic point of view, runtime manipulation of the
logging level boils down to something as simple as this:
// assume s_log is instance of Logger
s_log.setLevel(Level.WARN);
This sets the logging level for the
s_log
logger to
warn
. This means that messages output via, say,
debug(Object msg, Throwable throwable)
will be suppressed, because
warn
is stricter than
debug
.
The standard pattern for instantiating loggers that is used throughout WAF is as follows: