views:

257

answers:

3

So, here's my problem:
I have a message driven bean X and would like to make use of Logger in X's onMessage() method. Lets presume that I have a single instance of the bean running in my app server, hence, I would initialize log4j in ejbCreate(). This would mean I would have to do something like this:

public void ejbCreate() {
    PropertyConfigurator.configure(Classloader.getResourceAsStream("xyz_log4j.properties"));
}

However, this doesn't help. No matter what I do I always get my stream as null, I tried other versions : this.getClass().getStream() and ResourceBundle.

I jar'ed my properties file in to test.jar and added it under EAR libraries (I am using RAD7) and it got reflected in my manifest.mf.

Did anyone face this issue before? If yes, how did you solve it? Appreciate your help...

+2  A: 

If you're getting this from inside a JAR file, then you're missing an iniitial /:

Classloader.getResourceAsStream("/xyz_log4j.properties")

And depending on what directory contains the properties file, you have to specify a path to that directory relative to the top of the class hierarchy. For example, if this properties file is in the same directory as net.mine.Program, then you would do this:

Classloader.getResourceAsStream("/net/mine/xyz_log4j.properties")

I don't believe you can read from the META-INF directory using getResourceAsStream(), but I've never tried so perhaps there's a way to do it.

Eddie
+1  A: 

You could try hard coding the class name into the load.

<name of your class>.class.getResourceAsStream(fileName);

Alternatively you may want to look into SLF4J. Which is a facade that can sit on top of LOG4J. The API is mostly the same (same creator I believe), and SLF4J doesn't require an explicate initialization call, which simplifies things a bit.

James McMahon
Only if the properties file is in the same directory as the class.
Eddie
I think you are correct, but there maybe a way to adjust the path.
James McMahon
+1  A: 

I would not recommend configuring log4j in the EJB create method. Multiple EJBeans can be activated / passivated at the containers whim per the J2EE specification. So there is a possibility you end up configuring log4j multiple times. Recommend using startup beans which are guaranteed to be invoked only 1 time.

zkarthik
What is a startup bean? and how do you ensure it is invoked just once?
Jay
n application startup bean is a session bean that is loaded when an application starts. Application startup beans enable J2EE applications to run business logic automatically, whenever an application starts or stops normally albeit one time only.
zkarthik