1

We're writing a custom log4j appender for our application. The appender should log its events to a database. Now the problem I'm having is setting up the database connection. Our jdbc settings are in a file called jdbc.properties which is located directly under the WEB-INF folder.

I've tried accessing the properties file using the following code

InputStream stream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("jdbc.properties");

... but stream results in being null. Any ideas how I can load a properties file from the WEB-INF folder in a log4j appender without moving the properties file to another location?

Kim L
  • 6,323
  • 9
  • 35
  • 43
  • I think this will look for properties file in the WEB-INF/classes directory. A similar question: http://stackoverflow.com/questions/1108434/howto-load-a-resource-from-web-inf-directory-of-a-web-archive – Manish Dec 14 '11 at 08:29
  • I know, hence the comment about NOT moving the file. – Kim L Dec 14 '11 at 08:40
  • The problem is, that the appender is used, for example, when the server is starting, so there is no session and it's not bound to an application. – Kim L Dec 14 '11 at 08:53

2 Answers2

1

May be you can try,

 String  path =Thread.currentThread().getContextClassLoader().getResource("/").toURI().resolve("../jdbc.properties").getPath();
 Properties ps=new Properties();
 ps.load(new FileInputStream(path));
kv-prajapati
  • 90,019
  • 18
  • 141
  • 178
  • The appender is a freestanding class that only extends AppenderSkeleton, there is no getServletContext() method. Do I really have to create a ServletContextListener which stores the context in a static variable? – Kim L Dec 14 '11 at 08:50
  • @KimL - of course! you may also use `this.getClass().getResource("/").toURI().resolve("../jdbc.properties").toString()` in instance method of your class. – kv-prajapati Dec 14 '11 at 09:28
0

You should be able to get the file via the ServletContext. i.e.:

ServletContext ctx = ...
InputStream stream = ctx.getResourceAsStream("/WEB-INF/jdbc.properties"); 

Okay, just saw, that you don't have access to the ServletContext - forget the answer.

Isn't it possible to add the information for the jdbc connection into the log4j.properties? Why are you seperating the two?

Ulf Jaehrig
  • 731
  • 6
  • 11
  • Because rest of the application is using the jdbc.properties file. Don't want to have the same configuration in two places. – Kim L Dec 14 '11 at 09:15