Java – log4j properties file: how to configure

javalog4jlogging

My procedure for using log4j is 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)

Is this correct?
What happens if the initialization module is not defined? Where can I put the "log4j.properties" file such that I don't have to invoke propertyconfigurator.configure at all? If that's not possible, is it OK to invoke PropertyConfigurator.configure("path_to_file") in every method that uses a logger?

Best Answer

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.