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;
}
}
That is how you use it:
If you are wondering how to activate the Amazon SES SMTP server, check this out:
https://console.aws.amazon.com/ses/home#smtp-settings:
March 19th, 2012 at %I:%M %p
Good Post! On the other hand, some people argue that log statements pollute source code and decrease legibility. (I believe that the contrary is true). In the Java language where a preprocessor is not available, log statements increase the size of the code and reduce its speed, even when logging is turned off. Given that a reasonably sized application may contain thousands of log statements, speed is of particular importance.
Thanks for sharing