views:

330

answers:

2

Is it right that the procedure of using log4j looks like this:

1) put a .properties file somewhere in a project folder

2) in an initialization method, that runs only once, invoke

PropertyConfigurator.configure("path_to_file");

3) in every method we need to use logger we define a static logger variable and simply invoke getLogger(class)

I'm asking you this: what if the initialization module is not defined?

Where to put "log4j.properties" file so that we wouldn't need to invoke propertyconfigurator.configure at all, or if it's not possible,

is it ok to invoke PropertyConfigurator.configure("path_to_file") in every method that uses a logger?

+3  A: 

If you put it somewhere in the classpath, Log4J will automatically load it. A typical place for it is the source (or resource) root directory. That way it can get copied into the root directory of your jar too (if you create one from your class files).

The exact details for this depend on what build system you use. E.g. in Maven the convention is to put it in src/main/resources.

Péter Török
@Péter Török Ok, that's a different question, but in one phrase, a classpath by default, without providing -classpath java option, includes what folders of a .jar file?
EugeneP
@EugeneP Just covered this in my update :-)
Péter Török
+1  A: 

The default initialization procedure for log4j is documented in this section of the log4j tutorial. This explains in detail the steps that log4j takes to locate the logging configuration.

The simplest way to configure log4j is to put a the properties file somewhere that allows it to be found by the class loader using the name "/log4j.properties". There are other approaches that you can use as well that involve setting system properties, loading the properties file programmatically, or even instantiating the Loggers, Appenders and so on via the log4j APIs. (Not that the latter is a good idea ...)

(Putting the log4j properties file in "src/main/resources" in a Maven project is just one of a number of possible ways to get the file into your application's classpath root.)

Stephen C