log4j2 SMTP Appender: How to include previous messages with another level?

五迷三道 提交于 2019-12-03 03:40:36

This is currently not possible: the SMTP appender has a buffer where it captures log events before emailing them, but it will only capture the events that are configured for the target level (ERROR in your example). If you changed this to INFO, you would get email notifications for all INFO-level log messages (not just the ones preceding an ERROR-level message).

You can raise this as a feature request on the log4j issue tracker or log4j-user mailing list.


Correction: I was wrong, wrong, WRONG!

STMP Appender does have a buffer but it is meant to capture the last X (512 by default) INFO, DEBUG, TRACE-level messages that preceded the ERROR log event. So it is supposed to work like you expected (like the log4j-1.x SMTP appender works).

The SMTP Appender will fire an email when it gets an ERROR (or more severe)-level log event. So in your config you should not only send ERROR-level log events to this appender (or you'll miss the INFO, DEBUG, TRACE events that precede it).

In your config, change <AppenderRef ref="AsyncMailer" level="error"/> to <AppenderRef ref="AsyncMailer"/>.

That should fix the issue. If you still experience problems, someone else reported a similar issue and apparently found a workaround by adding a ThresholdFilter to the configuration:

<Appenders>
    <SMTP name="Mailer" suppressExceptions="false"
          subject="${subject}" to="${receipients}" from="${from}"
          smtpHost="${smtpHost}" smtpPort="${smtpPort}"
          smtpProtocol="${smtpProtocol}" smtpUsername="${smtpUser}"
          smtpPassword="${smtpPassword}" smtpDebug="false" bufferSize="20">

        <ThresholdFilter level="debug" onMatch="NEUTRAL" onMismatch="DENY" /> 
        <PatternLayout>
            <pattern>%d{dd-MM-yyyy HH:mm:ss,SSS} %5p %m%n</pattern>
        </PatternLayout>
    </SMTP>

    <Async name="AsyncMailer">
        <AppenderRef ref="Mailer"/>
    </Async>
</Appenders>
<Loggers>
    <Root level="info">
        <AppenderRef ref="AsyncMailer" />
    </Root>
</Loggers>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!