Send an email when an ERROR level log occurs with the logback SMTP Appender

things to do

Install FakeSMTP

FakeSMTP – FakeSMTP - Dummy SMTP server for developers

Install and start a dummy SMTP server for development.

pom.xml

pom.xml


	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4.7</version>
		</dependency>
	</dependencies>

logback.xml

Edit `` `logback.xml``` by referring to logback document Chapter 4 Appender #SMTPAppender.

src\main\resources\logback.xml


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

	<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>ERROR</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
		<smtpHost>localhost</smtpHost>
		<smtpPort>25</smtpPort>
		<to>[email protected]</to>
		<to>[email protected]</to>
		<from>[email protected]</from>
		<subject>TESTING: %logger{20} - %m</subject>
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%date %-5level %logger{35} - %message%n</pattern>
		</layout>
		<STARTTLS>true</STARTTLS>
		<asynchronousSending>false</asynchronousSending><!--See below-->
	</appender>

	<root level="DEBUG">
		<appender-ref ref="EMAIL" />
	</root>
</configuration>

asynchronousSending = false </ code> will be described later.

Sample code for operation check

Create a suitable spring-boot </ code> application.

HogeApplication.java


package kagamihoge.logmailsend;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HogeApplication implements CommandLineRunner {
	public static void main(String[] args) {
		SpringApplication.run(HogeApplication.class, args).close();
	}

	Logger logger = LoggerFactory.getLogger(HogeApplication.class);

	@Override
	public void run(String... args) throws Exception {
		logger.info("debug");
		logger.info("info");
		logger.error("error");
		logger.error("error with exception", new NullPointerException());
	}
}

State of execution

logback-smtp.jpg

About asynchronousSending = false

Since the sample code for operation check ends immediately after starting main, main ends before logback sends an email. Therefore, mail is not sent unless the asynchronous transmission mode is set to false.

Recommended Posts