Search code examples
javalog4jlog4j2

How to use log4j and log4j2 properies file to log into same file


I want to roll and compress log files based on size and time. I have found out that this can easily be performed with log4j2. The problem is many internal jars still use log4j for logging, which I want to be logged.

The possible solution I can think of here is by using log4j1.compatibility=true by keeping log4j.properties and log4j2.properties

What I can't figure out is how do I use RollingFileAppender in log4j.properties and log4j2 properties?

Please suggest me how can I use both the properties file(log4j and log4j2) to log to the same file with automatic compression when the specific size or time is reached.

Note: I tried using uk.org.simonsite.log4j.appender.TimeAndSizeRollingAppender but getting error NoClassDefError : org.apache.log4j.xml.unrecognizedelementhandler due to class is removed in log4j versions greater than v1.2.17.


Solution

  • Most libraries only use Log4j 1.x to log messages, they don't configure the logging system programmatically. Therefore you can simply replace log4j with log4j-1.2-api.

    The Log4j 1.x bridge (log4j-1.2-api) shares its configuration with Log4j 2.x Core, so you can use a native Log4j 2.x configuration file to configure a RollingFileAppender. No log4j.properties file or log4j1.compatibility property required.

    PS: Out of 4 configuration file formats supported by Log4j 2.x (cf. documentation) the properties format is probably the more convoluted. Personally I would choose one of the remaining 3 (XML, JSON or YAML). The XML format does not require additional dependencies.