Using log4j in EJB: where to configure the logging service?


EJB programming & troubleshooting: Using log4j in EJB: where to configure the logging service?

  1. Hi there,

    I have a question on how to use log4j in EJBs. Details:

    I want to provide a static final Logger instance in each bean class. This logger will be used by my bean instance to log some interesting messages. The log4j service should be initialized (by calling BasicConfigurator.configure() for example) only once before any message is logged. So where should i place the initialization code?

    I know that for a web app, i can define a ServletContextListener implementation to do the initialization work when my web app is loaded. Is there anything similar for EJB?

    Thanks in advance.
  2. I use a log4j.xml file in the APP-INF/classes folder in my EAR and put the log4j-<version>.jar in APP-INF/lib.

    It works out of the box. You do not have to even specify the configure method at startup.

    app server is WLS 8.1 sp 3
  3. Hi, thank you for your reply.

    I am using JONAS, which i think may be different from your WLS. Is there anyway to do the initialization server-independently?

  4. Well, here is an approach to ensure that before any logger instance is created, the log4j service is well configured.

    Firstly, i may provide a helper class like this:

    public class LogFactory {
        static {
        public static Logger getLogger(Class clazz) {
            return Logger.getLogger(clazz);

    Then in each of my bean class, i may get Logger instance by using the following code:

    private static final Logger log = LogFactory.getLogger(MyBean.class);

    But are there any better solutions? I mean, app server-independent solutions...