我在 log4j2-spring.xml 中配置的 Spring 引导项目中有一个 log4j2 gelf 追加器:
<Gelf name="graylog" host="https://example.com/gelf" version="1.1">
<PatternLayout pattern="%logger{1.} - %msg%n"/>
<!--- additional configuration --->
</Gelf>
gelf 追加器库是使用 maven 导入的:
<dependency>
<groupId>biz.paluch.logging</groupId>
<artifactId>logstash-gelf</artifactId>
<version>1.14.0</version>
</dependency>
该库提供了许多GelfSenders(biz.paluch.logging.gelf.intern.GelfSender(,例如GelfHTTPSender,GelfREDISSender等。如何扩展在log4j2-spring中配置的gelf追加器.xml以使用自定义GelfSender。
XML 中的<gelf ...>
appender 标记创建一个 biz.paluch.logging.gelf.log4j.GelfLogAppender
类使用 GelfSenderFactory 来创建要使用的 GeldSender。GelfSenderFactory 能够通过 Java Service Provider 接口加载 GelfSenderProvider(s(:
ServiceLoader<GelfSenderProvider> gelfSenderProvider
= ServiceLoader.load(GelfSenderProvider.class);
若要添加自定义 GelfSender,请创建一个扩展 GelfSenderProvider 接口的类:
package com.example.logging;
public class CustomGelfSenderProvider implements GelfSenderProvider {
@Override
public boolean supports(String host) {
// return true if this GelfSender is able to support sending to the given host
return true;
}
@Override
public GelfSender create(GelfSenderConfiguration configuration) throws IOException {
String host = configuration.getHost();
return new CustomGelfSender(host);
}
}
其中 CustomGelfSender 是 GelfSender 接口的实现:
package com.example.logging;
public class CustomGelfSender implements GelfSender {
private final String host;
public CustomGelfSender(String host) {
this.host = host;
}
@Override
public boolean sendMessage(GelfMessage message) {
// Send gelf message
return true;
}
@Override
public void close() {
// Anything to clean up on close
}
}
然后,通过将文件添加到src/main/resources/META-INF/services
中,将 CustomGelfSenderProvider 添加为 Java 服务提供程序接口服务。
文件名应该是服务实现的接口的完全限定类名,因此在本例中biz.paluch.logging.gelf.intern.GelfSenderProvider
.
此文件的内容是 GelfSenderProvider 实现的完全限定类名,因此在本例中com.example.logging.CustomGelfSenderProvider
.