Reputation: 12367
I'd like to log the error or the success of an EJB method that is participating in a transaction. Where shall I put the logging? As far as I know the transaction will be committed after my doSomething
has finished. So in that method I cannot be sure that the commit would be successful or not. That raised this question.
public class MyEjb {
@Inject
AnotherEjb anotherEjb;
@Inject
LoggerEjb logger;
public void doSomeThing() {
MyBean b = getSomething();
anotherEjb.persistSg(b);
/* logger.log is transaction if of attrubute NOT_SUPPORTED to
ensure separation from caller transaction */
logger.log("Did something successfully.");
}
}
public class AnotherEjb {
@Inject
EntitiyManager em;
public void persistSg(MyBean entity) {
em.persist(entity);
}
}
Upvotes: 2
Views: 1245
Reputation: 5199
Have you tried CDI's transactional observers?
http://docs.jboss.org/weld/reference/latest/en-US/html/events.html#d0e4075
This code fires an event:
@Inject Event<CategoryUpdate> categoryUpdateEvent;
public void someTransactionalMethod() {
CategoryUpdate categoryUpdate = new CategoryUpdate();
categoryUpdateEvent.fire(categoryUpdate);
}
And this piece of code observes the same event, but will be called only if the transaction succeeds:
public void refreshCategoryTree(@Observes(during = AFTER_SUCCESS) CategoryUpdate event) {
......
}
Upvotes: 2
Reputation: 33946
Use bean-managed transactions, which gives you control over the begin/commit/rollback of a UserTransaction. I would suggest adding the begin/commit/rollback logic to an EJB interceptor, since that lets you reuse the logic across multiple EJBs.
Upvotes: 1
Reputation: 7652
Unfortunately, I think the answer is "it depends" - I don't believe there is a general purpose answer that applies in every circumstance. For instance, you don't say what is calling these EJB's. If your architecture has a "business service layer" as it common, then it might be both practical and sensible to put the logging in there....
With respect to the logging itself, I would recommend that you not do what you are doing above. First, don't call .log itself. Rather call a specific log level (DEBUG, INFO, etc). Next, check for this log level being enabled prior to calling the log statement. Yes, this is a PITA, but has measurable results performance-wise. Finally, try to never log a simple bit of text as you have done above. Logging is a chance to provide some useful information that you had in your hands to the log file. You miss this chance! If you log, at the very least log something about the bean you just found, created, or what not.
Best of luck!
Upvotes: -1