Migrating from log4j 1.2 to log4j 2 - how to get l

2019-06-16 17:33发布

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?

2条回答
等我变得足够好
2楼-- · 2019-06-16 17:48

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.

查看更多
虎瘦雄心在
3楼-- · 2019-06-16 18:03

I've added accessors for

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

See our SVN trunk.

查看更多
登录 后发表回答