Tuesday, September 4, 2007

Log4J - email notification of production errors

There are a couple of things I try to do before I sit down to write Java code for even the smallest project (cause they always grow). One is creating an ant build script and the other is creating a log4j configuration file and adding log4j to my library path. I used to sprinkle System.out.println's throughout my code and now I've gotten in the habit of using the logging library.

I hadn't used the SMTPAppender, but recent issues with production code got me thinking about it so I'd have a heads up before users starting yelling. Below is the log4j.properties file that's worked well so far. The code is all custom so I have total control of all log.error and log.fatal statements, so when I get an email I know exactly what the issues is. Wouldn't be possible if I still used System.out.


log4j.rootLogger=ERROR, SMTPAPPENDER, rolling

log4j.appender.screen=org.apache.log4j.ConsoleAppender
log4j.appender.screen.layout=org.apache.log4j.PatternLayout
log4j.appender.screen.layout.ConversionPattern=%d %-4r [%t] %-5p %c %x - %m%n

log4j.appender.rolling=org.apache.log4j.RollingFileAppender
log4j.appender.rolling.Threshold=DEBUG
log4j.appender.rolling.File=/tmp/csufresno-hrsrecruit-cnv.log
log4j.appender.rolling.MaxFileSize=20480KB
log4j.appender.rolling.MaxBackupIndex=5
log4j.appender.rolling.layout=org.apache.log4j.PatternLayout
log4j.appender.rolling.layout.ConversionPattern=%d %p [%c{4}] %M %m%n

log4j.appender.SMTPAPPENDER.To=me@myaddress.com
log4j.appender.SMTPAPPENDER.layout=org.apache.log4j.PatternLayout
log4j.appender.SMTPAPPENDER=org.apache.log4j.net.SMTPAppender
log4j.appender.SMTPAPPENDER.Subject=[hrsrecruit] ERROR
log4j.appender.SMTPAPPENDER.BufferSize=512
log4j.appender.SMTPAPPENDER.From=myapp@myserver.com
log4j.appender.SMTPAPPENDER.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.appender.SMTPAPPENDER.SMTPHost=mysmtp.server.com

log4j.logger.edu.csufresno.cis=INFO



Just a note, took me a few runs to figure out that I needed mail.jar and activation.jar in my classpath. After that, smooth sailing.

4 comments:

Robbin Alexander said...

Have you tried the conversion pattern in the subject line. I need to display the host name in the subject line.

Venki said...

is it possible to give multiple user ids separated with comma as in below?
log4j.appender.SMTPAPPENDER.To
=me@myaddress.com,
mycollegue@myaddress.com

doma said...

The default implementation does not allow you to use the patterns in the subject. Though, it is fairly easy to implement this, see http://lajosd.blogspot.com/2009/09/log4j-smtpappender-exception-info-in.html

Steve Paul said...

Its a good post! I like the way you expressed. emergency notification