May 19, 2010

Log4j Gmail SmtpAppender, send log emails via Gmail on Errors !

Log4j gives SMTPAppender for sending emails on logging. This SMTP Appender works good in  most of the cases, except TLS/SSL SMTP setups. Gmail works on the same SSL/TLS setup, so any one who wants to configure the default log4j SMTPAppender with Gmail will be troubled with strange Java Mail errors.

Though this problem can be easily solved by writing a Log4j Custom SMTP Appender.

“GmailSMTPAppender“ - Custom SMTPAppender for GMAIL

“GmailSMTPAppender” is the solution to the default log4j SMTPAppender SSL/TLS issue. GmailSMTPAppender is basically an extension to existing log4j SMTPAppender. It just overrides two methods from SMTPAppender i.e.

  1. protected Session createSession()
  2. protected void sendBuffer()

So by this inheritance GmailSMTPAppender utilizes the log4j’s SMTPAppender for most of the logic and specializes few methods for Gmail specific handling.

How to Install GmailSmtpAppender in my project ?

GmailSMTPAppender is open source, here is the project landing page [link]. Following are the steps to install this appender to your project.

  • Checkout the project source from here. This source is checking of a full Eclipse “Java project”.
  • Copy to your source folder.
  • Only dependencies are log4j-1.2.16.jar and java mail.jar. You can replace them with latest version if required or use your existing ones.
  • Copy and replace available here as required. You have to change the usual SMTPAppender settings for "log4j.appender.EMAIL". This is explained in detail below.
  • Thats it, all done !!. Use Logger.error() to send email notifications.

What about Google APPS Account ?

GmailSmtpAppender works fine with both normal Gmail accounts and Google apps account. The same SMTP Host will go for Google apps accounts. So just update the SMTPUser/Pass with From/To addresses and you are done.

Source Code & DEPENDENCIES ?

The complete code + dependencies is hosted on GoogleCode. You can checkout the code from here.

Setting up

Here is the sample You can change or copy stuff like appenders from it as required. GmailSMTPAppender has not exposed any new appender settings. So just use your usual SMTPAppender settings and they will work fine with GmailSMTPAppender too.

#Google Code Project
#My Blog :

log4j.rootLogger=ERROR, Console,R, Console, R, EMAIL

log4j.appender.Console.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

# Turn off debugging if not required
log4j.appender.EMAIL.Subject=Email Notification from Gmail SMTP Appender
log4j.appender.EMAIL.layout.ConversionPattern=%p %t %c - %m%n

Sample ERROR Emails !

log4j error email in gmail inbox

Log4j error email body


Let me know in case of issues.