Log4j SmtpAppender - exception in subject

1.2k views Asked by At

I use log4j for sending emails with exception.

My log4j configuration:

log4j.rootLogger=info, stdout, errmail

log4j.appender.errmail=cz.toby.utils.log.ErrSmtpAppender
[email protected]
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("[email protected]");
        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.

1

There are 1 answers

1
Terrell Plotzki On BEST ANSWER

@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));