5.6. Logging
Before Seam, even the simplest log message required verbose code:
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); }
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); }
Except for entity bean components (which require the
log
variable to be static), this will work regardless of whether the log
variable is declared static.
String concatenation occurs inside the
debug()
method, so the verbose if ( log.isDebugEnabled() )
guard is unnecessary. Usually, we would not even need to explicitly specify the log category, since Seam knows where it is injecting the log
.
If
User
and Product
are Seam components available in the current contexts, the code is even more concise:
@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 automatically chooses whether to send output to log4j or JDK logging — if log4j is in the classpath, it will be used; if not, Seam uses JDK logging.