log4j properties file: how to configure?
My procedure for using log4j is this:
- put a .properties file somewhere in a project folder
- in an initialization method, that runs only once, invoke PropertyConfigurator.configure("path_to_file")
- 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_fil开发者_StackOverflowe") in every method that uses a logger?
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
.
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.)
精彩评论