I am using log4net.
When Application gives an error, I want to send e-mail just for errors. How should I do that ?
My Config File :
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net>
<appender name="SMTPAppender" type="log4net.Appender.SMTPAppender">
<authentication value="Basic" />
<to value="xxx@xxx" />
<from value="yyy@yyy" />
<username value="user" />
<password value="pass" />
<subject value="ERROR" />
<smtpHost value="host" />
<port value="25" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN" />
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread] %-5level %logger %newline %message%newline%newline%newline" />
</layout>
</appender>
<root>
<level value="INFO"></level>
</root>
<logger name="SMTPAppender">
<level value="INFO"></level>
<appender-ref ref="SMTPAppender"></appender-ref>
</logger>
</log4net>
</configuration>
I am trying to test in NUnit:
[TestFixture]
public class TestClass
{
[Test]
public void Test()
{
ILog logger = LogManager.GetLogger(typeof(TestClass));
logger.Error("test mail");
}
}
I am probably doing something wrong.
EDIT:
<logger name="Yuartz.Tests.TestClass">
<level value="INFO"></level>
<appender-ref ref="SMTPAppender"></appender-ref>
</logger>
namespace Yuartz.Tests
{
using log4net;
using log4net.Config;
[TestFixture]
public class TestClass
{
[Test]
public void Test()
{
XmlConfigurator.Configure();
var logger = LogManager.GetLogger("SMTPAppender");
logger.Error("test mail");
logger.Info("test mail");
}
}
}
In your example you use the full name of the type (TestClass) to retrieve your logger. It will use this name to resolve the logger or create a new one when not found.
If you want this line of code to return the SMTPAppender logger, then you need to rename it in the config as follows:
If you don’t want to change the configuration then you need to retrieve your logger by its actual name. The following returns the logger named “SMTPAppender”.
My advice is to just change the name in the configuration and keep retrieving the logger by type as you currently do.
Also make sure that you read your configuration.