我在OSGi环境中编写了一个Log4j2自定义Converter插件,并将log4j2与ops4j-pax-logging一起使用。自定义字段为tenantId
,我在log4j2.xml中将其称为%tenantId
。当我运行程序时,日志打印为{thread-name} enantId。
插件类
package com.test.logging.converters;
@Plugin(name = "TenantIdConverter", category = "Converter")
@ConverterKeys({"tenantId"})
public class TenantIdConverter extends LogEventPatternConverter {
public TenantIdConverter(String name, String style) {
super(name, style);
}
public static TenantIdConverter newInstance(String[] options) {
return new TenantIdConverter("tenantId", "tenantId");
}
@Override
public void format(LogEvent event, StringBuilder toAppendTo) {
toAppendTo.append(getTenantID());
}
public String getTenantID() {
String tenantId = "1234";
if (tenantId == null) {
tenantId = "[]";
}
return tenantId;
}
}
的pom.xml
<dependency>
<groupId>org.ops4j.pax.logging</groupId>
<artifactId>pax-logging-api</artifactId>
<version>1.10.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.ops4j.pax.logging</groupId>
<artifactId>pax-logging-log4j2</artifactId>
<version>1.10.1</version>
</dependency>
<plugin>
<groupId>org.ops4j</groupId>
<artifactId>maven-pax-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<executions>
<execution>
<id>log4j-plugin-processor</id>
<goals>
<goal>compile</goal>
</goals>
<phase>process-classes</phase>
<configuration>
<proc>only</proc>
<annotationProcessors>
<annotationProcessor>org.apache.logging.log4j.core.config.plugins.processor.PluginProcessor</annotationProcessor>
</annotationProcessors>
</configuration>
</execution>
</executions>
</plugin>
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO" name="log-test" packages="com.test.logging.converters">
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%-5p %d [%tenantId] %c: %m%n"/>
</Console>
<RollingFile name="RollingFile" fileName="logs/log4j2app.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout>
<Pattern>%-5p %d [%tenantId] %c: %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>
答案 0 :(得分:0)
解决。
为org.ops4j.pax.logging.pax-logging-log4j2
创建了一个osgi片段,并将appender放在这个碎片包中。
<Fragment-Host>org.ops4j.pax.logging.pax-logging-log4j2</Fragment-Host>