问题描述
我正在将我的应用程序从log4j 1.2迁移到log4j 2.0
我有现有代码:
Enumeration appenders = logger.getAllAppenders(); . . . fileBackupIndex = rollingFileAppender.getMaxBackupIndex();
在log4j 2.0中,我找不到替换上方Java代码的方法.如何获取所有附录的列表以及如何以编程为RollingFile Appender定义的最大值?
推荐答案
使用log4j2,API和Core之间存在分离.这使团队可以在不违反客户端代码的情况下对实施进行更改.
因此,如果您的代码取决于实施详细信息,请注意,将来可能会更改并且您的代码可能会破裂.
也就
Logger logger = LogManager.getLogger(); Map<String, Appender> appenderMap = ((org.apache.logging.log4j.core.Logger) logger).getAppenders();
您可以在地图上循环,直到找到RollingFileAppender为止.从这一点开始,它真的很丑陋...您想要的信息全部都在私人领域,因此您需要使用反射来执行以下操作:
- 获取FileAppender的"经理"字段并将其施放给RollingFileManager
- 获取经理的"策略"字段,并将其投入到DefaultrolloverStrategy
- 获取DefaultrolloverStrategy的" Maxindex"字段
这显然很脆弱...如果您真的需要此功能,则可以在Log4J-Dev邮件列表上请求此功能或创建JIRA票.获得此功能的最快方法是,如果您提供了具有功能请求的补丁.
其他推荐答案
我已经为
添加了访问者- MinIndex,Maxindex和CompressionLevel.
- TriggerPolicy和RolloverStrategy.
请参阅我们的SVN TRUNK.
问题描述
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?
推荐答案
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.
其他推荐答案
I've added accessors for
- minIndex, maxIndex, and compressionLevel.
- triggeringPolicy and rolloverStrategy.
See our SVN trunk.