java如何读取自定义log4j2_如何自定义log4j2 RollingFileAppender?

使用内置查找的替代方法是创建自定义查找 . 这可以使用log4j2插件在几行代码中完成 . 然后,您的自定义查找会提供您希望在每次翻转时在文件 Headers 中显示的确切值 .

插件代码看起来像这样:

package com.mycompany;

import org.apache.logging.log4j.core.LogEvent;

import org.apache.logging.log4j.core.config.plugins.Plugin;

import org.apache.logging.log4j.core.lookup.AbstractLookup;

import org.apache.logging.log4j.core.lookup.StrLookup;

/**

* Looks up keys from a class SomeClass which has access to all

* information you want to provide in the log file header at rollover.

*/

@Plugin(name = "setu", category = StrLookup.CATEGORY)

public class SetuLookup extends AbstractLookup {

/**

* Looks up the value of the specified key by invoking a

* static method on SomeClass.

*

* @param event The current LogEvent (ignored by this StrLookup).

* @param key the key to be looked up, may be null

* @return The value of the specified key.

*/

@Override

public String lookup(final LogEvent event, final String key) {

return com.mycompany.SomeClass.getValue(key);

}

}

然后,在您的配置中,您可以使用模式布局的 Headers 在每次翻转时输出:

filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}.log.gz">

%d %m%n

log4j2手册包含有关构建/部署custom plugins的详细信息 . 简要总结:

最简单的方法是使用Maven构建jar;这将导致log4j2注释处理器在jar中生成二进制索引文件,因此log4j2可以快速找到您的插件 .

另一种方法是在log4j2.xml配置的 packages 属性中指定插件类的包名称:

...

更新:请注意,在您的查找实现中,您可以根据需要进行创作 . 例如:

package com.mycompany;

public class SomeClass {

private static AtomicLong count = new AtomicLong(0);

public static String getValue(final String key) {

if (count.getAndIncrement() == 0) { // is this the first call?

return ""; // don't output a value at system startup

}

if ("FULL".equals(key)) {

// returns info to shown on rollover, nicely formatted

return fullyFormattedHeader();

}

return singleValue(key);

}

....

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值