javalog4jsmtpappender

Log4j smtp appender to send just one email for all errors


I have a program that processes ids. Some ids get multiple errors on the ETL. I am setting up log4j smtp to send an email when I encounter an error or fatal. Right now it will send 5 emails for five errors for one program run. I would like to aggregate them into one email. I have log4j properties set instead of xml.

properties. I hid to and from

log4j.rootCategory=DEBUG,stdout,fileout, sendMail

log4j.appender.sendMail=org.apache.log4j.net.SMTPAppender
log4j.appender.sendMail.Threshold=Error
log4j.appender.sendMail.SMTPHost=mailhost
log4j.appender.sendMail.From=hidden
log4j.appender.sendMail.To=hidden
log4j.appender.sendMail.Subject=Failure
log4j.appender.sendMail.BufferSize=1
#log4j.appender.sendMail.evaluatorClass=TriggerLogEvent
log4j.appender.sendMail.layout=org.apache.log4j.PatternLayout
log4j.appender.sendMail.layout.ConversionPattern=%m

Theres just not much info out on log4j smtp appender.


Solution

  • how about creating another class to aggregate the error messages and create a new logger for that class

    so first you create a class that will hold all of the error messages for a particular id

    public class TestLog4j {
    
    static Logger log = Logger.getLogger(TestLog4j.class.getName());
    
    int id;
    ArrayList<String> errors,fatals;
    
    public void addError(String e)
    {
    
        this.errors.add(e);
    }
    public void addFatal(String f)
    {
    
        this.fatals.add(f);
    }
    
    public void sendLogs() {
    
        SimpleDateFormat sdf = new SimpleDateFormat();
    
        for (String e : this.errors)
        {
             log.error("Error Message at "+sdf.format(new Date()) + " for id "+ this.id);
        }
        for (String f : this.fatals)
        {
              log.fatal("Fatal Message at "+sdf.format(new Date()) + " for id "+ this.id);
        }
    
    
        }
    
    }
    

    now, you only call your sendLogs method after you are sure that ll the messages have been aggregated. also in your log4j.properties, you can add another smtpappender for this TestLog4j class. you can obviously optimize the code

    log4j.properties

    log4j.logger.package.TestLog4j = ERROR, sendmail
    # turn off additivity
    log4j.additivity.package.TestLog4j = false