Sunday, August 16, 2009

Sending Email Using Apache Log4J

I mentioned that I was interested in using Log4j's SMTPAppender to e-mail me messages when errors occured in my webapp. I discovered how easy it is. Here's how to configure it.

Add the following configuration settings to Log4j.XML


<appender name="mail" class="org.apache.log4j.net.SMTPAppender">

<param name="SMTPHost" value="YourSMTPHostIP" />

<param name="From" value="FromEmailAddress" />

<param name="To" value="ToEmailAdressSeperatedByComma" />

<param name="Subject" value="Subject" />

<param name="BufferSize" value="1" />

<param name="threshold" value="error" />

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern"

value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />

</layout>

</appender>

2 comments:

Unknown said...

nice post..
but can you exaplain it more?

Gayan Dissanayake - said...

Yes Ruwini
here is my full log4j.xml file please look at that and tell is that enough or what else you need to know ,ask me question then I can answer it
Thanks for referring my blog
Gayan


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >

<log4j:configuration>

<appender name="file"

class="org.apache.log4j.RollingFileAppender">

<param name="maxFileSize" value="1954KB" />

<param name="maxBackupIndex" value="20" />

<param name="File" value="C://Sun//AppServer//domains//domain1//logs/SmsEngine.log"
/>

<!--<param name="File" value="/his/sjasee8_2/domains/domain1/logs/Transport.log"/-->

<param name="threshold" value="info" />

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern"

value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />

</layout>

</appender>

<appender name="debugfile"

class="org.apache.log4j.RollingFileAppender">

<param name="maxFileSize" value="1954KB" />

<param name="maxBackupIndex" value="20" />

<param name="File" value="debug.log" />

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern"

value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />

</layout>

<filter class="org.apache.log4j.varia.LevelRangeFilter">

<param name="LevelMin" value="debug" />

<param name="LevelMax" value="debug" />

</filter>

</appender>

<appender name="mail" class="org.apache.log4j.net.SMTPAppender">

<param name="SMTPHost" value="xxx.xxx.xxx.xxx" />

<param name="From" value="SmsEngineErrorCatcher@echannelling.com" />

<param name="To" value="pdngayan@gmail.com" />

<param name="Subject" value="[LOG] ...APPLICATION ERROR :( .." />

<param name="BufferSize" value="1" />

<param name="threshold" value="error" />

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern"

value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />

</layout>

</appender>

<root>

<priority value="debug"></priority>

<appender-ref ref="debugfile" />

<appender-ref ref="file" />

<appender-ref ref="mail" />

</root>

</log4j:configuration>