Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating from log4j 1.2 to log4j 2 - how to get list of all appenders and rolling file strategy

I am in the process of migrating my application from log4j 1.2 to log4j 2.0

I have existing code:

Enumeration appenders = logger.getAllAppenders();
.
.
.
fileBackupIndex = rollingFileAppender.getMaxBackupIndex();

In log4j 2.0 I could not find way to replace above java code. How to get list of all appenders and how to get the max value defined for RollingFile appender programatically?

like image 935
user1957983 Avatar asked Jan 23 '14 09:01

user1957983


2 Answers

With log4j2, there is a separation between API and CORE. This allows the team to make changes to the implementation without breaking client code.

So, if your code depends on implementation details, be aware that in the future this may change and your code may break.

That said, you can get a map of the appenders like this:

Logger logger = LogManager.getLogger();
Map<String, Appender> appenderMap = 
        ((org.apache.logging.log4j.core.Logger) logger).getAppenders();

You can loop over the map until you find a RollingFileAppender. From this point it gets really ugly... The information you want is all in private fields, so you would need to use reflection to do the following:

  • get the fileAppender's "manager" field and cast it to RollingFileManager
  • get the manager's "strategy" field and cast it to DefaultRolloverStrategy
  • get the defaultRolloverStrategy's "maxIndex" field

This would obviously be pretty fragile... If you really need this you can request this feature on the log4j-dev mailing list or create a JIRA ticket. The quickest way to get this feature is if you provide a patch with the feature request.

like image 52
Remko Popma Avatar answered Oct 14 '22 15:10

Remko Popma


I've added accessors for

  • minIndex, maxIndex, and compressionLevel.
  • triggeringPolicy and rolloverStrategy.

See our SVN trunk.

like image 22
Gary Gregory Avatar answered Oct 14 '22 15:10

Gary Gregory