我正在将我的应用程序从log4j
迁移到log4j2
API。迁移时,我发现使用了custom
patternlayouts
,patternparsers
和patternconverters
。我不知道如何使用log4j2插件实现这些更改。任何人都可以帮助我如何将此自定义布局TestPatternLayout
转换为log4j2。非常感谢。
PFB使用log4j
实现自定义模式布局的完整详细信息。
TestPatternLayout:
public class TestPatternLayout extends PatternLayout {
@Override
protected PatternParser createPatternParser(String pattern) {
return new TestPatternParser(pattern);
}
}
TestPatternParser:
public class TestPatternParser extends PatternParser {
private static final char Test_CHAR = 'e';
private static final char DATETIME_CHAR = 'd';
public TestPatternParser(String pattern) {
super(pattern);
}
@Override
protected void finalizeConverter(char c) {
switch (c) {
case Test_CHAR:
currentLiteral.setLength(0);
addConverter(new TestPatternConverter());
break;
default:
super.finalizeConverter(c);
}
}
}
TestPatternConverter:
public class TestPatternConverter extends PatternConverter {
@Override
protected String convert(LoggingEvent event) {
String testID = ObjectUtils.EMPTY_STRING;
if(TestLogHandler.isTestLogEnabled()) {
TestContextHolder contextHolder = TestLogHandler.getLatestContextHolderFromStack(event.getThreadName());
if(contextHolder != null) {
testID = contextHolder.getTestIDForThread(event.getThreadName());
}
else{
testID = TestContextHolder.getTestIDForThread(event.getThreadName());
}
}
return testID;
}
}
log4j.xml中的布局定义:
<appender name="TEST_LOG_FILE" class="org.apache.log4j.RollingFileAppender">
...
<layout class="com.test.it.logging.TestPatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c{1}] [TestId: %e] [%t] %m%n"/>
</layout>
...
</appender>
答案 0 :(得分:4)
您只需要创建一个新的Plugin
并扩展LogEventPatternConverter
:
@Plugin(name = "TestPatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({"e"})
public final class TestPatternConverter extends LogEventPatternConverter {
/**
* Private constructor.
* @param options options, may be null.
*/
private TestPatternConverter(final String[] options) {
super("TestId", "testId");
}
/**
* Obtains an instance of pattern converter.
*
* @param options options, may be null.
* @return instance of pattern converter.
*/
public static TestPatternConverter newInstance(final String[] options) {
return new TestPatternConverter(options);
}
/**
* {@inheritDoc}
*/
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
String testID = ObjectUtils.EMPTY_STRING;
if(TestLogHandler.isTestLogEnabled()) {
TestContextHolder contextHolder = TestLogHandler.getLatestContextHolderFromStack(event.getThreadName());
if(contextHolder != null) {
testID = contextHolder.getTestIDForThread(event.getThreadName());
}
else{
testID = TestContextHolder.getTestIDForThread(event.getThreadName());
}
}
toAppendTo.append(testID);
}
}
并更新您的配置:
<Appender type="RollingFile" name="TEST_LOG_FILE" fileName="${filename}">
<Layout type="PatternLayout">
<Pattern>%d %-5p [%c{1}] [TestId: %e] [%t] %m%n</Pattern>
</Layout>
</Appender>
应该是全部。请参阅Extending log4j2 了解更多详情。