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

给你一囗甜甜゛ 提交于 2019-12-23 07:38:41

问题


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?


回答1:


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.




回答2:


I've added accessors for

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

See our SVN trunk.



来源:https://stackoverflow.com/questions/21303746/migrating-from-log4j-1-2-to-log4j-2-how-to-get-list-of-all-appenders-and-rolli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!