我写了一个测试程序来验证logback相对于log4j的性能提升。但令我惊讶的是,我遇到了这个奇怪的问题。我正在使用它们的异步和文件追加器将一些 200k 日志消息循环写入文件。但是,每次,它只记录大约 140k 条消息,然后就停止了。它只是打印我的最后一条日志语句,表明它已将所有内容写入缓冲区并且程序终止。如果我只是用 Log4j 运行同一个程序,我可以在日志文件中看到所有 200k 条消息。是否有任何基本的架构差异使这种情况发生?无论如何要避免它?我们正在考虑从 log4j 切换到 logback,现在这让我重新思考。
这是我的 logback 配置:
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>logback.log</file>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
</encoder>
</appender>
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="FILE" />
</appender>
<root level="info">
<appender-ref ref="ASYNC" />
</root>
</configuration>
这是我的代码--------------------
public static void main(String[] args) throws InterruptedException {
org.slf4j.Logger logbackLogger = LoggerFactory
.getLogger(LogbackTest.class);
List<Integer> runs = Arrays.asList(1000, 5000, 50000, 200000);
ArrayList<Long> logbackRuntimes = new ArrayList<>(4);
for (int run = 0; run < runs.size(); run++) {
logbackLogger.info("------------------------>Starting run: "
+ (run + 1));
// logback test
long stTime = System.nanoTime();
int i = 0;
for (i = 1; i <= runs.get(run); i++) {
Thread.sleep(1);
logbackLogger
.info("This is a Logback test log, run: {}, iter: {}",
run, i);
}
logbackRuntimes.add(System.nanoTime() - stTime);
logbackLogger.info("logback run - " + (run + 1) + " " + i);
}
Thread.sleep(5000);
// print results
logbackLogger.info("Run times:");
logbackLogger
.info("Run\tNoOfMessages\tLog4j Time(ms)\tLogback Time(ms)");
for (int run = 0; run < runs.size(); run++) {
logbackLogger.info((run + 1) + "\t" + runs.get(run) + "\t"
+ logbackRuntimes.get(run) / 10e6d);
}
}
最佳答案
根据 the documentation :
[...] by default, when less than 20% of the queue capacilty remains, AsyncAppender will drop events of level TRACE, DEBUG and INFO keeping only events of level WARN and ERROR. This strategy ensures non-blocking handling of logging events (hence excellent performance) at the cost loosing events of level TRACE, DEBUG and INFO when the queue has less than 20% capacity. Event loss can be prevented by setting the discardingThreshold property to 0 (zero).
关于java - Logback 将我的日志消息丢失到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19107813/