10

Integrating sending mail functionality with LogBack in Scala

 3 years ago
source link: https://blog.knoldus.com/integrating-sending-mail-functionality-with-logback-in-scala/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Integrating sending mail functionality with LogBack in Scala

Reading Time: < 1 minute

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 :

xxxxxxxxxx
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 :

xxxxxxxxxx
<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 :

xxxxxxxxxx
<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


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK