Integrating sending mail functionality with LogBack in Scala


Few days ago, I had the requirement that whenever there will be an exception in the application, we should get an email for this. Earlier, I was just logging the error log using LogBack :

val logger: Logger = LoggerFactory.getLogger(this.getClass())
logger.error("................")

To do this, there are 2 ways :
1. Use the email sending code at every place wherever i have used logger.error.
2. Use the SMTPAppender of logback which sends email by itself whenever logger.error will be called.

So I tried with 2nd solution.

SMTPAppender :
We have to provide following settings for this in logback.xml :

<appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
		<smtpHost>smtp.gmail.com</smtpHost>
		<smtpPort>587</smtpPort>
		<STARTTLS>true</STARTTLS>
		<username>USERNAME</username>
		<password>PASSWORD</password>
		<asynchronousSending>false</asynchronousSending>
		<to>EMAIL-IDS</to>
		<from>NAME</from>
		<subject>ERROR: %logger{20} - %m</subject>
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%date %-5level %logger - %message%n</pattern>
		</layout>
	</appender>
	<root level="info">
		<appender-ref ref="EMAIL" />
	</root>

There is one important thing to be remember, email would work only for logger.error(). Other than this ,it would not be work
If you want to append one more logger then do as follows :

<logger name="com.example.foo" level="debug">
		<appender-ref ref="CONSOLE" /
</logger>

Code for this sample is present on the Knoldus Github
For more details, click here

About Rishi Khandelwal

Sr. Software Engineer having more than 5 years industry experience. He has working experience in various technologies such as Scala, Java, Play, Akka, Lift Web, Spark, ElasticSearch, Backbone.js, html5, javascript, Less, Amazon EC2, WebRTC, SBT
This entry was posted in Akka, Cloud, Java, Play Framework, Reactive, Scala, Web. Bookmark the permalink.

2 Responses to Integrating sending mail functionality with LogBack in Scala

  1. Reblogged this on Play!ng with Scala and commented:

    The SMTPAppender accumulates logging events in one or more fixed-size buffers and sends the contents of the appropriate buffer in an email after a user-specified event occurs. SMTP email transmission (sending) is performed asynchronously. By default, the email transmission is triggered by a logging event of level ERROR. Moreover, by default, a single buffer is used for all events.

    http://logback.qos.ch/manual/appenders.html#SMTPAppender

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s