Log4j2 configuration format with best coverage

Viewed 172

Log4j2 currently supports 4 configurations formats [1]: XML, JSON, YAML, and properties syntax. I couldn't find in the documentation if all the formats are exactly equivalent in terms of feature coverage.

Is it possible to use all features of Log4j2 in every format or there are certain formats that lack some expressiveness?

I vaguely remember in the past that I had some trouble setting up a feature in the property syntax while it was working in the XML syntax; it could be my lack of knowledge at the time instead of a missing feature but if somebody can provide a reference about equivalence or not it would be helpful.

[1] https://logging.apache.org/log4j/2.x/manual/configuration.html#

1 Answers

This deserves a longer answer than I am going to give here.

The answer to the question is that from a Log4j perspective they are all equivalent. But from a user's perspective they are not.

  1. In general, XML files allow anything that can be expressed as an XML attribute to also be specified as an XML element. So on PatternLayout you can do either:

    XML Example

  2. The log4j configuration is hierarchical. For example, all Logger elements are configured under the Loggers element. Specific configuration for a Logger is inside that Logger element. XML, JSON, and YAML are all hierarchical by nature. Properties are not. To emulate that hierarchy you have to prepend every element with the name of the element that precedes it in the tree. This can get messy, which is why I never use the properties syntax and resisted implementing it in the first place.

  3. The properties format is the only format that doesn't require any dependencies outside of java.base (in Java 9+ terms). Unfortunately, XML is not part of the minimal Java distribution in Java 9+ and JSON/YAML never were.

So yes, you should be able to express any configuration in any of the formats, but figuring out what it should be in the properties format sometimes requires expressing it in one of the other formats just so you can figure out what the property equivalent syntax should be.

Related