我一般来说,如果你想通过 Log4j 和 Slf4j 完成日志记录,你需要添加适当的依赖项。这是我们的一个项目的配置:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
这将带来适当的部门。
这是log4j.properties
文件的内容。
log4j.rootLogger=INFO, ${logger-name}, SPLUNK
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.SPLUNK=org.apache.log4j.DailyRollingFileAppender
log4j.appender.SPLUNK.File=${catalina.home}/logs/worker-splunk.log
log4j.appender.SPLUNK.Append=true
log4j.appender.SPLUNK.Encoding=UTF-8
# This is a filter that will filter out junk we do not want to sent to Splunk
log4j.appender.SPLUNK.filter.1=app.utils.SplunkLogFilter
log4j.appender.SPLUNK.layout=org.javalite.logging.JsonLog4jLayout
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.FILE.File=${catalina.home}/logs/worker.log
log4j.appender.FILE.Append=true
log4j.appender.FILE.Encoding=UTF-8
log4j.appender.FILE.layout=org.javalite.logging.JsonLog4jLayout
这logger-name
是一个 Maven 过滤的属性。在本地,它被解析为CONSOLE
,当应用程序被构建时,它被解析为FILE
. 这样,我们可以在开发过程中在控制台上观察日志。
该类SplunkLogFilter
如下所示:
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;
public class SplunkLogFilter extends Filter {
private static final String[] EXCLUDED_LOGGERS = new String[]{"***ServiceImpl", "app.utils.ProcessUtil"};
private static final String[] EXCLUDED_MESSAGES = new String[]{"****Command"};
@Override
public int decide(LoggingEvent event) {
String loggerName = event.getLoggerName();
for (String excludedLogger : EXCLUDED_LOGGERS) {
if(loggerName.equals(excludedLogger)){
return Filter.DENY;
}
}
String message = event.getMessage().toString();
for (String excludedMessage : EXCLUDED_MESSAGES) {
if(message.contains(excludedMessage)){
return Filter.DENY;
}
}
return Filter.NEUTRAL;
}
}
因此,我们并行登录到两个文件,其中一个被发送到 Splunk。Splunk 文件较小,因此我们为 Splunk 支付的费用较少,但我们保留完整文件以防万一。