Thursday, August 07, 2008

Log4Net SmtpAppender and sending emails with log messages

Since my client asked me if it was possible to generate emails for log entries on an error/fatal level I took a look into the Log4Net SmtpAppender. In your project you may need to implement a similar function and in that case you may use a log4net configuration like the following one-

93 <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">

94 <to value="" />

95 <from value="" />

96 <Username value=""></Username>

97 <password value="" ></password>

98 <authentication value="Basic"></authentication>

99 <subject value="test logging message from log4net" />

100 <smtpHost value="" />

101 <bufferSize value="512" />

102 <lossy value="true" />

103 <evaluator type="log4net.Core.LevelEvaluator">

104 <threshold value="INFO"/>

105 </evaluator>

106 <layout type="log4net.Layout.PatternLayout">

107 <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />

108 </layout>

109 </appender>

110

111 <root>

112 <level value="DEBUG"/>

113 <appender-ref ref="LogFileAppender"/>

114 <appender-ref ref="SmtpAppender"/>

115 </root>

I had to use the username and password as my server requires authentication. Now, in case your server don't demand authentication, you can avoid using these two nodes as well as the authentication node. You can also specify the port name if your smtp server is not using the default port.

Doing so keeps you posted of the error conditions early since sometimes finding an error entry by periodically checking is missed. Hope this helps someone with similar need.