栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何自定义log4j2 RollingFileAppender?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何自定义log4j2 RollingFileAppender?

使用内置查找的一种替代方法是创建自定义查找。使用log4j2插件只需几行代码即可完成。然后,您的自定义查询将提供您希望在每次翻转时在文件头中显示的确切值。

插件代码如下所示:

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;@Plugin(name = "setu", category = StrLookup.CATEGORY)public class SetuLookup extends AbstractLookup {        @Override    public String lookup(final LogEvent event, final String key) {        return com.mycompany.SomeClass.getValue(key);    }}

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

<RollingFile name="RollingFile" fileName="logs/app.log"  filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}.log.gz">  <!-- use custom lookups to access arbitrary internal system info -->  <PatternLayout header="${setu:key1} ${setu:key2}">    <Pattern>%d %m%n</Pattern>  </PatternLayout>  <Policies>    <TimebasedTriggeringPolicy />  </Policies></RollingFile>

log4j2手册详细介绍了如何构建/部署自定义插件。简要摘要:

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

替代方法是在log4j2.xml配置的

packages
属性中指定插件类的软件包名称:

<Configuration status="warn" packages="com.mycompany">  ...

更新:请注意,在您的查找实现中,您可以根据需要获得创意。例如:

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);    }    ....}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427881.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号