April 9, 2020
Estimated Post Reading Time ~

Send Mail via Log4j with SMTP Appender

Grails supports sending all log messages(error,fatal, etc.) to a support team or to yourself, by email (Gmail account), via log4j with SMTP Appender.

1. For this we have to do some configuration in Config.groovy as shown below:

a // import SMTPAppender and Log4j Lever classes
import org.apache.log4j.net.SMTPAppender
import org.apache.log4j.Level

...

// Mail server Configration
mail.error.server = 'smtp.gmail.com'
mail.error.port = 587
mail.error.username = 'senderEmailId@gmail.com'
mail.error.password = 'senderPassword'
mail.error.to = 'receiver@gmail.com'
mail.error.subject = 'Mail Subject'
mail.error.starttls = true
mail.error.debug = false

....

// log4j Configration.
log4j = {
System.setProperty 'mail.smtp.starttls.enable', config.mail.error.starttls.toString()
System.setProperty 'mail.smtp.port', config.mail.error.port.toString()

// To send all errors or bigger level messages in email via SMTPAppender
appender new SMTPAppender(name: 'smtp', to: config.mail.error.to,
from: config.mail.error.from, subject: config.mail.error.subject, threshold: Level.ERROR, SMTPHost: config.mail.error.server,
SMTPUsername: config.mail.error.username, SMTPDebug: config.mail.error.debug.toString(),
SMTPPassword: config.mail.error.password,
layout: pattern(conversionPattern:'%d{[ dd.MM.yyyy HH:mm:ss.SSS]} [%t] %n%-5p %n%c %n%C %n %x %n %m%n'))

....

root {
error 'stdout', 'smtp'
additivity = false
}
}


NOTE: If you are using a version below Grails2 then you will have to use mail.error.port instead of config.mail.error.port and mail.error.server instead of config.mail.error.server in log4j block, etc.
2. Add dependency for mail.jar and activation.jar.
3. Add log.error(“Error Message”), when you want to mail error messages.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.