1.加入发送邮件的包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.配置logback-spring.xml
<!--logback异常邮件发送-->
<!-- 邮件配置 -->
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义后,可以使“${}”来使用变量。 -->
<springProperty scope="context" name="smtpHost" source="spring.mail.host" />
<springProperty scope="context" name="username" source="spring.mail.username" />
<springProperty scope="context" name="password" source="spring.mail.password" />
<springProperty scope="context" name="mailSubject" source="spring.mail.error.subject" />
<springProperty scope="context" name="mailTo" source="spring.mail.error.to" />
<appender name="MAIL" class="ch.qos.logback.classic.net.SMTPAppender">
<smtpHost>${smtpHost}</smtpHost>
<smtpPort>465</smtpPort>
<username>${username}</username>
<password>${password}</password>
<SSL>true</SSL>
<asynchronousSending>true</asynchronousSending>
<from>${username}</from>
<to>${mailTo}</to>
<subject>${mailSubject}: %logger{0} </subject>
<charsetEncoding>UTF-8</charsetEncoding>
<cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker">
<!-- 每个电子邮件只发送一个日志条目 -->
<bufferSize>1</bufferSize>
</cyclicBufferTracker>
<!--HTML展示-->
<layout class="ch.qos.logback.classic.html.HTMLLayout"/>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!--错误级别(只会提示大于该级别的错误)-->
<level>ERROR</level>
</filter>
</appender>
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="debug"/>
<appender-ref ref="error"/>
<appender-ref ref="warn"/>
<appender-ref ref="MAIL"/>
</root>
效果:
3.logback 获取不到自定义变量值解决
logback错误日志
no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]
原因
logback.xml的加载早于application.yml配置文件,在logback.xml中使用<springProperty>标签来获取配置文件中的变量值,读取不到而报出错误信息。
解决方法:
1.将logback.xml重命名为logback-spring.xml。
2.将logback.xml重命名为自己指定的名字(xxx.xml),然后在配置文件中指定生效的文件。
logging:
config: classpath:xxx.xml