Last Updated: February 25, 2016
·
1.735K
· fsamir

AmazonSESSMTPAppender for Log4J

Log4J can easily send e-mail notifications every time an error occurs. It is particularly interesting and a very powerful functionality for production environments. However, the default SMTPAppender lacks support for SSL enabled SMTP servers and it is also not easily configurable according to the environment.
This is an enhanced version of the Original SMTPAppender, which supports SSL and is environment aware.

package com.dattein.logging;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.security.Security;
import java.util.Properties;

public class SMTPAppender extends org.apache.log4j.net.SMTPAppender {

    public SMTPAppender() {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    }

    @Override
    protected boolean checkEntryConditions() {
        //Obviously you have to use your own environment aware mechanisme, instead of the line below
        return Environment.isProduction();
    }

    @Override
    protected Session createSession() {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.host", getSMTPHost());
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", getSMTPPort());
        properties.put("mail.smtp.socketFactory.port", getSMTPPort());
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", " false");
        properties.setProperty("mail.smtp.quitwait", " false");
        Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(getSMTPUsername(), getSMTPPassword());
            }
        });
        return session;
    }
}

Finally, that is how you use it:

<appender name="mail-appender" class="com.dattein.logging.SMTPAppender">
<param name="SMTPHost" value="email-smtp.us-east-1.amazonaws.com">
<param name="SMTPUsername" value="<USERNAME>">
<param name="SMTPPassword" value="<PASSWORD>">
<param name="SMTPPort" value="465">
<param name="BufferSize" value="64">
<param name="Subject" value="[ERROR]">
<param name="To" value="errors@dattein.com">
<param name="From" value="donotreply@dattein.com">
<param name="Threshold" value="ERROR">
        <layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="My App [%p] %c{2} %x - %m%n">
        </layout>
    </appender>

    <root>
        <level value="DEBUG">
        <appender-ref ref="mail-appender">
 </appender-ref></level></root>