1

我设置了一个 Spring-boot 应用程序,当抛出异常时,它每 24 小时最多将 10 条日志发送到特定的电子邮件。我使用logback它可以工作,但是在实现自定义 SMTPAdapter(以限制电子邮件速率)之后,电子邮件中的 HTMLLayout 只有标题,没有内容,我必须在自定义 SMTPAppender 中更改什么?

想法:
使用默认工作,经过研究我发现我必须在自定义附加程序中设置属性(日期...),但我没有找到任何解决方案。

图片:

电子邮件

对于自定义 SMTPAppender,我使用了以下代码:
https ://stackoverflow.com/a/31081552/6865330

ScheduledSMTPAppender 的代码:

public class ScheduledSMTPAppender extends SMTPAppender {

private final ThreadFactory tf = r -> {
    Thread t = new Thread(r, "ScheduledSMTPAppender Thread");
    t.setDaemon(true); //make daemon or it will prevent the program to exit
    return t;
};
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, tf);

private final List<ILoggingEvent> events = new ArrayList<>();

private int maxMessages = 10;

public ScheduledSMTPAppender() {
    super();
}

public ScheduledSMTPAppender(EventEvaluator<ILoggingEvent> eventEvaluator) {
    super(eventEvaluator);
}

@Override public void start() {
    super.start();
    scheduler.scheduleAtFixedRate(this::sendEmail, 1, 1, TimeUnit.MINUTES);
}

@Override protected void sendBuffer(CyclicBuffer<ILoggingEvent> cb, ILoggingEvent lastEventObject) {
    if (events.size() > maxMessages) sendEmail();
}

private synchronized void sendEmail() {
    try {
        if (events.isEmpty()) return;
        ILoggingEvent lastEvent = events.get(events.size() - 1);
        events.remove(events.size() - 1);
        CyclicBuffer<ILoggingEvent> cb;

        if (events.isEmpty()) {
            cb = new CyclicBuffer<>(1);
        } else {
            cb = new CyclicBuffer<>(events.size());
            for (ILoggingEvent e : events){
                cb.add(e);
            }
        }
        super.sendBuffer(cb, lastEvent);
        events.clear();
    } catch (Exception e) {
        //Important to have a catch all here or the scheduled task will die
        addError("Error occurred while sending e-mail notification.", e);
    }
}

//this allows to make "maxMessages" a parameter of your appender
public int getMaxMessages() { return maxMessages; }

public void setMaxMessages(int maxMessages) { this.maxMessages = maxMessages; }

}

4

0 回答 0