使用Spring启动将日志发送到电子邮件

时间:2015-09-22 15:25:41

标签: spring email spring-boot logback amazon-ses

我正在试图弄清楚如何配置我的Spring启动项目,将日志消息发送到电子邮件,但还没有成功。没有发送电子邮件,没有明显的错误。

我的logback.xml:

doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                myCallback.onConnected();
                return null;
            }
        }).when(mGoogleApiClient).connect();

我的application.yaml:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>

    <appender name="mail" class="ch.qos.logback.classic.net.SMTPAppender">
        <smtpHost>email-smtp.eu-west-1.amazonaws.com</smtpHost>
        <from>dev@example.com</from>
        <to>dev@example.com</to>
        <subject>Something went wrong</subject>
        <layout class="ch.qos.logback.classic.html.HTMLLayout"/>

        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>DEBUG</level>
        </filter>
    </appender>

    <root level="INFO">
        <appender-ref ref="mail"/>
    </root>
</configuration>

我做错了什么?有没有不同的方法在Spring Boot中将日志消息发送到电子邮件?

2 个答案:

答案 0 :(得分:3)

请使用此功能(PS:不要尝试从属性文件加载属性进行回溯,因为它在启动时不可见&amp;如果仍然希望设置属性然后将它们作为JVM参数提供为其可见的回溯): -

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <appender name="dbgMailer" class="ch.qos.logback.classic.net.SMTPAppender">
      <smtpHost>email-smtp.eu-west-1.amazonaws.com</smtpHost>
      <smtpPort>25</smtpPort>
      <from>dev@example.com</from>
      <to>dev@example.com</to>
      <subjectStr>Something went wrong</subjectStr>
      <layout class="ch.qos.logback.classic.html.HTMLLayout"/>
      <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
          <level>DEBUG</level>
      </filter>
  </appender>
    <root level="DEBUG">
        <appender-ref ref="dbgMailer" />
    </root>
</configuration>

答案 1 :(得分:1)

您在application.yaml中配置Spring邮件模块,而不是为logback appender提供必要的数据。您可能需要在SMTP服务器中进行身份验证凭据:

<appender name="mail" class="ch.qos.logback.classic.net.SMTPAppender">
    <smtpHost>email-smtp.eu-west-1.amazonaws.com</smtpHost>
    <username>user</username>
    <password>user</password>
    <from>dev@example.com</from>
    <to>dev@example.com</to>
    <subject>Something went wrong</subject>
    <layout class="ch.qos.logback.classic.html.HTMLLayout"/>

    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>DEBUG</level>
    </filter>
</appender>

另见: