Interview Questions

Log4j - Snmp Trap Appender

In this article lets discuss about sending SNMP Traps using log4j.

SNMP Traps are messages which are sent to a server or SNMP Trap receiver listening on a particular port.

In any java application, we use logging framework such as log4j to log errors, information etc,. for debugging. Consider a scenario where it is required to send SNMP Traps when the db is down or any server down or any unusual events in the application. Whenever such an event is logged , the same can be sent as a SNMP Trap using log4j. To make this work we need to use SNMP Trap appender.

Lets see how to configure SNMP Trap appender using log4j. For sending any SNMP Trap we need to know entities such as ManagementHostName, TrapListener port, EnterpriseOID, senderIPaddress, Sender port,generic Trap type, specific Trap type, TrapOid and community string.

These entities has to be appended your log4j.properties as follows.

log4j.properties Configuration

log4j.rootCategory=WARN,TRAP_LOG
log4j.appender.TRAP_LOG=org.apache.log4j.ext.SNMPTrapAppender
log4j.appender.TRAP_LOG.ImplementationClassName=org.apache.log4j.ext.JoeSNMPTrapSender
log4j.appender.TRAP_LOG.ManagementHost=127.0.0.1
log4j.appender.TRAP_LOG.ManagementHostTrapListenPort=162
log4j.appender.TRAP_LOG.EnterpriseOID=1.3.6.1.4.1.24.0
log4j.appender.TRAP_LOG.LocalIPAddress=127.0.0.1
log4j.appender.TRAP_LOG.LocalTrapSendPort=161
log4j.appender.TRAP_LOG.GenericTrapType=6
log4j.appender.TRAP_LOG.SpecificTrapType=12345678
log4j.appender.TRAP_LOG.ApplicationTrapOID=1.3.6.1.4.1.24.12.10.22.64
log4j.appender.TRAP_LOG.CommunityString=public
log4j.appender.TRAP_LOG.Threshold=DEBUG
log4j.appender.TRAP_LOG.layout=org.apache.log4j.PatternLayout
log4j.appender.TRAP_LOG.layout.ConversionPattern=%d,%p,%t,%c,%m%n

How to test the above configuration?

Have a look at the following class, which sends SNMP Traps using log4j api.

Whenever an exception is logged in the below code, a Trap message will be sent to a SNMP Trapreceiver listening in the port 162 as specified in the log4j.properties.

package in.techdive.snmp;

import org.apache.log4j.Logger;

public class SNMPTrapSenderTest
{
    protected final Logger trapLog = Logger.getLogger(getClass());

    public static void main(String[] args)
    {
        SNMPTrapSenderTest snmpTest = new SNMPTrapSenderTest();
        snmpTest.sendSnmpTraps();
    }

    public void sendSnmpTraps()
    {
        try
        {
            // your code here for example: which tries to access a server
        }
        catch (Exception e)
        {
            trapLog.info("Server Not found");
        }
    }
}

Download any Trap receiver tool available in net to test the application.

Note: snmpTrapAppender_1_2_9.jar file has to added to the lib folder in your project.