Log4J & Email
Among other appenders, Log4J comes with an SMTP appender that is dramatically useful when you need to alert someone of an event; here's two examples :
- Using unsecured connection
- Using secure connection, such as SSL or TLS.
Using unsecured connection
In order to use a simple and unsecured smpt server, all you have to do is configure log4j.properties so that it includes something like this
log4j.appender.SENDMAIL.To = A_USER@SOMEWHERE.SOMETHING
log4j.appender.SENDMAIL.From = system.alert@fermasoft.com
log4j.appender.SENDMAIL.SMTPHost = some.unsecured.smtp
#some servers do not use the default port : change this as you need
log4j.appender.SENDMAIL.SMTPPort = 25
log4j.appender.SENDMAIL.SMTPDebug = true
log4j.appender.SENDMAIL.SMTPPassword=XXXXXXXX
log4j.appender.SENDMAIL.SMTPUsername=XXXXXXXX
# the maximum number of logging events to collect in a cyclic buffer
log4j.appender.SENDMAIL.BufferSize = 1
log4j.appender.SENDMAIL.LocationInfo = true
log4j.appender.SENDMAIL.Subject = "System Error"
log4j.appender.SENDMAIL.layout = org.apache.log4j.PatternLayout
log4j.appender.SENDMAIL.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
and the job is done
Using Secure Connection
The problem comes when your mailserver uses secure connection as TLS or SSL, then you need to add the following javax.mail.Session properties:
System.setProperty("mail.smtp.socketFactory.port", "465");
System.setProperty("mail.smtp.socketFactory.fallback", "false");
so that the following configuration snippet can actually work :
log4j.appender.SMTP=org.apache.log4j.net.SMTPAppender
# the maximum number of logging events to collect in a cyclic buffer
log4j.appender.SMTP.BufferSize=1
log4j.appender.SMTP.From=system.alert@fermasoft.com
log4j.appender.SMTP.LocationInfo=true
log4j.appender.SMTP.SMTPDebug=true
log4j.appender.SMTP.SMTPHost=smtp.gmail.com
log4j.appender.SMTP.SMTPPassword=PASSWORD
log4j.appender.SMTP.SMTPUsername=USER@gmail.com
log4j.appender.SMTP.Subject=System Error
log4j.appender.SMTP.To=A_USER@SOMEWHERE.SOMETHING
Happy logging !
Recent Comments