It is always better to get notified as soon as any major issues / exceptions occurred in the Application, instead of manually going thorugh huge logs to find probable exception messages. Apache log4j provides out of the box log Appender (called SMTPAppender) to send email alerts for the log level configured in log4j configuration file.

Technologies used in this article

  1. Apache log4j
  2. SLF4J
  3. Javamail
  4. JDK 1.6
  5. Eclipse 3.7

1. Create a Java Project and a Class with 'main' method

Create a java project ('Log4jMailNotifer') and a class ('Log4jMailNotiferTest') with 'main' method

2. Copy jars

Create a 'lib' folder inside the project folder and copy the following jars 'slf4j-api-1.7.1.jar', 'slf4j-log4j12-1.7.1.jar', 'log4j-1.2.17.jar' and 'mail-1.4.jar' to the newly created 'lib' folder. These jars are already included in the full source code provided with this tutorial in the 'Download Source Code' section.

3. Configure Build Path

Add slf4j, log4j and mail jars to the build path of your project as shown below.
Configure Build Path

4. Write Code

The following code will generate an exception and that exception will be logged inside catch block. In the next step we'll configure log4j.xml so that the error message logged in the catch block can trigger an email notification.

File: Log4jMailNotiferTest.java

package com.srccodes.examples;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * 
 * @author Abhijit Ghosh
 * @version 1.0
 */
public class Log4jMailNotiferTest {
    private static Logger logger = LoggerFactory.getLogger(Log4jMailNotiferTest.class);
 
 
    /**
     * To test whether fatal log sent to email id or not.
     * 
     * @param args
     */
    public static void main(String[] args) {
        try {
            // Generate exception
            throw new Exception("Generating exception to test Log4j mail notification...");
        } catch (Exception ex) {
            logger.error("Test Result : ", ex);
        }
    }
}

5. log4j configuration

Configure SMTPAppender in log4j.xml

File: log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 
    <appender name="mailAppender" class="org.apache.log4j.net.SMTPAppender">
        <param name="BufferSize" value="50" />
        <param name="SMTPHost" value="smtp.mail.yahoo.com" />
        <param name="SMTPPort" value="587" />
        <param name="SMTPUsername" value="[email protected]" />
        <param name="SMTPPassword" value="mypassword" />
        <param name="From" value="[email protected]" />
        <param name="To" value="[email protected]" />
        <param name="Subject" value="Testing Log4j mail notification" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{ISO8601}]%n%n%-5p%n%n%c%n%n%m%n%n" />
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMin" value="error" />
            <param name="LevelMax" value="fatal" />
        </filter>
    </appender>
 
    <root>
        <priority value="info" />
        <appender-ref ref="mailAppender" />
    </root>
</log4j:configuration>

Note:
Provide correct SMTPHost, SMTPPort, authentication details (SMTPUsername and SMTPPassword), From, To (comma separated list) and email Subject. Also provide minimum and maximum log level in the 'LevelRangeFilter'. The number of logging events delivered in this e-mail depend on the value of 'BufferSize' option.

6. Final project structure

Overall project structure will look like as shown below
log4j SMTPAppender overall project structure

7. Run Your Code to Generate Log

On execution of the main method, error log will be generated and same will will be emailed using SMTPAppender.
log4j SMTPAppender overall project structure

Download SrcCodes

All code samples shown in this post are available in the following link Log4jMailNotifer.zip

References