Who is not totally fed up with seeing noisy code like this?
private static final Log log = LogFactory.getLog(CreateOrderAction.class);
public Order createOrder(User user, Product product, int quantity) {
if ( log.isDebugEnabled() ) {
log.debug("Creating new order for user: " + user.username() +
" product: " + product.name()
+ " quantity: " + quantity);
}
return new Order(user, product, quantity);
}
It is difficult to imagine how the code for a simple log message could possibly be more verbose. There is more lines of code tied up in logging than in the actual business logic! I remain totally astonished that the Java community has not come up with anything better in 10 years.
Seam provides a logging API that simplifies this code significantly:
@Logger private Log log;
public Order createOrder(User user, Product product, int quantity) {
log.debug("Creating new order for user: #0 product: #1 quantity: #2", user.username(),
product.name(), quantity);
return new Order(user, product, quantity);
}
It doesn't matter if you declare the log
variable static or not—it will work either way, except for entity bean components which require the log
variable to be static.
Note that we don't need the noisy if ( log.isDebugEnabled() )
guard, since string concatenation happens
inside
the debug()
method. Note also that we don't usually need to specify the log category explicitly, since Seam knows what component it is injecting the Log
into.
If User
and Product
are Seam components available in the current contexts, it gets even better:
@Logger private Log log;
public Order createOrder(User user, Product product, int quantity) {
log.debug("Creating new order for user: #{user.username} product: #{product.name}
quantity: #0", quantity);
return new Order(user, product, quantity);
}
Seam logging automagically chooses whether to send output to log4j or JDK logging. If log4j is in the classpath, Seam with use it. If it is not, Seam will use JDK logging.