Technologies used in this article :

  1. log4j

  2. SLF4J

  3. Javamail

  4. JDK 1.6

  5. Eclipse 3.7

Related Posts

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
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 Source Code

 

References