0

I want to initialize Log4j basically as the first thing in an EAR application, so that all other modules and classes can use the logger.

How can I do this?

I have an EAR with a WAR and multible EJB jars. At the moment, I am initializing it in a init() method of a Servlet, but I appear to have classes (e.g. Timers) that are loaded and initialized before that.

I need to initialize Log4j programmatically because I want to provide a custom location for the Log4j config file. I can't pass the file in via config parameters during app server or container startup.

The app server is Websphere 8.5, but a general standards-compliant solution is preferred.

jhyot
  • 3,733
  • 1
  • 27
  • 44

1 Answers1

0

I don't think any initialization is required programatically. It can be initialized via Java options ie. (-Dlog4j...) when starting your container.

See How to initialize log4j properly?

Community
  • 1
  • 1
pmartin8
  • 1,545
  • 1
  • 20
  • 36
  • I need to do it programmatically at the moment, because I am hardcoding a custom config file name (not ideal but I will have to live with it). I edited the question to address this. – jhyot Sep 22 '15 at 13:49
  • Why don't you do -Dlog4j.configuration=myCustomFile.properties – pmartin8 Sep 22 '15 at 13:51
  • I can't pass config parameters when deploying or starting up or an application. The app server is not under my control and has many apps running. I have inherited the deployment etc. processes of this application and don't want to go changing things around. Eventually I might be able to clean everything up a bit, but for the moment I wanted just to solve the most pressing problem of some log messages going missing because log4j init is not the first thing that happens. – jhyot Sep 22 '15 at 13:56
  • I'm pretty sure the JEE container will instanciate the EJB (service layer) before any servlet (the web layer). Servlets need EJBs to work, not the otherway around. A workaround could be to initialize log4j in the first EJB that gets created? – pmartin8 Sep 22 '15 at 14:01
  • 1
    You could use '@Startup' '@Singleton' to get it started. – pmartin8 Sep 22 '15 at 14:03
  • Thanks, I will have a look at those annotations – jhyot Sep 22 '15 at 14:36
  • we decided to go with a WebContextListener, which is the first entry in the web.xml. This means that this class will get called first. But after reading about the `@Startup` and `@Singleton` annotations, those would probably have worked too. – jhyot Oct 08 '15 at 09:08