我正在尝试将Logback
与SMTPAppender
一起用作我的日志记录解决方案。我有一个附加到appender
的评估程序,它会触发每100个记录错误的电子邮件。在大多数情况下,这是正常的,但我注意到,如果我在循环中快速创建错误,以触发多个电子邮件,只有最后一封电子邮件被发送,具有正确的内容。这似乎是一种竞争条件,其中第一封电子邮件未完成创建/发送,第二封电子邮件在创建时覆盖第一封电子邮件。有没有其他人经历过这个或找到了解决方案。我的logback配置附在下面。
<configuration>
<appender name="emailAppender" class="${logback.emailAppenderClass}">
<evaluator class="com.wdp.common.logging.logback.evaluators.CountingLoggerEvaulator">
<limit>100</limit>
</evaluator>
<to>${logback.emailNotificationRecipientStr}</to>
<from>${logback.emailNotificationFromStr}</from>
<smtpHost>${logback.smtpHost}</smtpHost>
<subject>Logback logs for facebook-ads-processes</subject>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d [Thread:%t] %p [%c] - %m%n</pattern>
</layout>
<cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker">
<bufferSize>${logback.cyclicBufferSize}</bufferSize>
</cyclicBufferTracker>
</appender>
</configuration>
这是评估员:
public class CountingLoggerEvaulator extends EventEvaluatorBase<ILoggingEvent> implements EventEvaluator<ILoggingEvent> {
//if limit is not set in configuration, this will cause it to send one email for each message received.
private int limit = 100;
private int counter = 0;
public void setLimit(int limit) {
this.limit = limit;
}
public int getLimit() {
return limit;
}
@Override
public boolean evaluate(ILoggingEvent expr) throws NullPointerException, EvaluationException {
counter++;
if (counter == limit) {
counter = 0;
return true;
} else {
return false;
}
}
}
非常感谢任何帮助。
答案 0 :(得分:1)
问题是SMTPAppender的asynchronousSending属性默认为true。我把它设置为false并且它正常工作
答案 1 :(得分:0)
您应该使您的Evaluator线程安全 - 例如使用AtomicInteger
:
public class CountingLoggerEvaulator extends EventEvaluatorBase<ILoggingEvent> implements EventEvaluator<ILoggingEvent> {
//if limit is not set in configuration, this will cause it to send one email for each message received.
private int limit = 100;
private AtomicInteger counter = new AtomicInteger();
public void setLimit(int limit) {
this.limit = limit;
}
public int getLimit() {
return limit;
}
@Override
public boolean evaluate(ILoggingEvent expr) throws NullPointerException, EvaluationException {
int curValue = counter.incrementAndGet();
if (curValue >= limit) {
return counter.compareAndSet(curValue, 0);
} else {
return false;
}
}
}