4

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.

jantobola
  • 688
  • 2
  • 10
  • 28
  • Is there an exception occurring in you catch block? Can you post what is happening in there rather than swallowing it? Also why not use setSubject() form the SMTPAppender similar to setFrom() why are you calling it directly on the msg? – Terrell Plotzki Jan 30 '12 at 17:30
  • This try/catch block is not important now. If will be the situation when I can't get host name with "InetAddress.getLocalHost().getHostName()", so it doesn't mind It just set the subject from the properties file without host name ... what I want is to get a name of an exception which I caught wherever in the application and set it into the subject. I hope this is understandable :) ... and msg.setSubject() or setSubject(), you're right, I can use this variant. – jantobola Jan 31 '12 at 09:12
  • Oh, I cannot use setSubject(), it doesn't work for some reason. I have to call msg.setSubject() but it's not the main point of my previous question. – jantobola Jan 31 '12 at 09:27

1 Answers1

2

@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));
Terrell Plotzki
  • 2,014
  • 17
  • 17