Search code examples
javaexceptionlog4jsmtpappender

Log4j SmtpAppender - exception in subject


I use log4j for sending emails with exception.

My log4j configuration:

log4j.rootLogger=info, stdout, errmail

log4j.appender.errmail=cz.toby.utils.log.ErrSmtpAppender
log4j.appender.errmail.to=my_email@email.cz
log4j.appender.errmail.subject=Error - 
log4j.appender.errmail.layout=org.apache.log4j.HTMLLayout
log4j.appender.errmail.threshold=debug

It works perfectly, but what I want is dynamicaly change the content of subject with names of exceptions.

my appender looks like this:

    public class ErrSmtpAppender extends SMTPAppender {

    @Override
    public void activateOptions() {
        setSMTPHost("xxxxx");
        setFrom("from_email@email.cz");
        setBufferSize(50);
        super.activateOptions();
        try {
            msg.setSubject(msg.getSubject() + ", node: " + InetAddress.getLocalHost().getHostName());
        } catch (Exception e) {
            // do nothing, only cannot set host to subject
        }
    }

}

How can I set subject with a name of exception programmatically? I was trying to find it on the internet, but I found only similar themes but not what I exactly want.


Solution

  • @Toby Ok I misunderstood what you are trying to achieve. You are wanting the log message in the e-mail subject?

    I think for that you will need to access the CyclicBuffer cb of the Appender something like:

    msg.setSubject("Logged Message String" + cb.get(cb.length()).getMessage());
    

    Or you may need to do an ObjectRenderer as well

    ThreadGroupRenderer stackTraceRenderer = new ThreadGroupRenderer();
    msg.setSubject("First 100 Chars of Stack Trace: " + stackTraceRenderer(cb.get(cb.length()-1).getMessage()).substring(0,99));