log4j.properties vs log4j.xml

2020-02-07 17:48发布

问题:

I was asked to move from properties style configuration to xml style. The process itself is straightforward and it is not causing me any trouble, I was simply curious why I got asked this and I looked for the reason. I found this nice post Why chose XML over properties files for Log4J configuration? (more than 3 years old but still the most informative I could find), which was pointing pointing to this even older tutorial. They state

Properties can be defined by a properties file or by an XML file.

Log4j looks for a file named log4j.xml and then for a file named log4j.properties. Both must be placed in the src folder.

I checked it out and, contrary to the statement, found out that Log4j looks first for the properties file and in a second time for xml. In fact, if I keep both in the same folder, the output is formatted according to the properties file. So, am I misunderstood the statement? Is it simply wrong? The statement has been made for log4j 1.2.14 while I am on log4j 1.2.17, is it possible the log4j team changed the priority? I couldn't find any related documentation, but it will be a strange trend inversion since the xml looked to be the preferred way to configure log4j

回答1:

Have a look at the JavaDoc. The documentation of the PropertyConfiguratorClass (log4j.properties) points out that

The PropertyConfigurator does not handle the advanced configuration features supported by the DOMConfigurator such as support custom ErrorHandlers, nested appenders such as the AsyncAppender, etc.

So the DOMConfigurator (log4j.xml) offers advanced options.

Beside that you can have (at least a simple) validity check of log4j.xml files using the provided log4j.dtd.

If youd do not make use of the advanced features it is needless to change from properties to xml files.

What you really should think about is to change from log4j to log4j 2 beta or even slf4j. Development of log4j has stopped and the founder of it (@Ceki) invented slf4j.



回答2:

As per FrVaBe's answer, the PropertyConfigurator class does not handle the advanced features that XML can support.

It's worth noting one of the more useful advanced options (only available log4j.xml) is the ability to filter on a specific log level or range of log levels using LevelMatchFilter and DenyAllFilter

A good example can be seen here.



标签: log4j