我正在使用log4j2。我已经为它定义了自定义的附加器和模式,并以编程的方式设置:
public static void initCustomLogging(List<Appender> appenders) {
LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
Configuration configuration = loggerContext.getConfiguration();
LoggerConfig rootLoggerConfig = configuration.getLoggerConfig("");
for (Appender appender : appenders) {
appender.start();
rootLoggerConfig.addAppender(appender, Level.INFO, null);
}
loggerContext.updateLoggers();
}
在这里我创建了我的appender,比如:
private static final String CUSTOM_PATTERN = "{\"time\":\"%d{HH:mm:ss.SSS}\",\"data\":%msg}";
private static final Layout CUSTOM_LAYOUT = PatternLayout.newBuilder()
.withPattern(CUSTOM_PATTERN)
.build();
Appender appender = CustomAppender.createAppender("custom",CUSTOM_LAYOUT)
但是,我想将自定义参数添加到我的模式中,例如[%requestinfo],在这里它将调用某个静态方法。我知道我可以这样定义我的转换器:
@Plugin(name = "MyConverter", category = "Converter")
@ConverterKeys({"requestData"})
public class MyConverter extends LogEventPatternConverter {
private MyConverter (final String name, final String style) {
super(name, style);
}
public static MyConverter newInstance(final String[] options) {
return new MyConverter ("requestData", "requestData");
}
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
toAppendTo.append(getRequestId());
}
private String getRequestData() {
String data= // some static method call
if (data== null) {
data= "-";
}
return data;
}
}
如果我是通过xml配置文件配置log4j2,那么这将自动获取并为我配置。但是,由于我是以编程方式配置它的-如何将它添加到我的布局中?我看不出做这件事的方法。
谢谢你的帮助!
暂无答案!
目前还没有任何答案,快来回答吧!