使用内置查找的替代方法是创建自定义查找 . 这可以使用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);
}
....
}