Header Ads

Log4Net Sending an Email When an Error Occurs using Asp.net and C#

If Error occurs Log4net sending email and store log details in your system

1.Now put this web.config/app.config file in configuration tag.
<!--Log4net Configuration-->
<configuration>
<configsections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net">
</section></configsections>


<!--ErrorLog store in system-->

<log4net debug="true">
<appender name="File" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString">
<conversionpattern value="C:\%date{dd-MM-yyyy}\%date{HH}-Error.log">
</conversionpattern></file>
<appendtofile value="true">
<maxsizerollbackups value="10">
<datepattern value=".txt">
<rollingstyle value="Date">
<staticlogfilename value="false">
<layout type="log4net.Layout.PatternLayout">
<conversionpattern value="%date{ABSOLUTE} [%thread] %-5level %logger.%method() - %message [%identity]%newline">
</conversionpattern></layout>
</staticlogfilename></rollingstyle></datepattern></maxsizerollbackups></appendtofile></appender>

<!--ErrorLog sending to Mail-->

<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender,log4net">
<to value="[email protected]">
<from value="[email protected]">
<subject value="ErrorLogmessage">
<smtphost value="LocalHost">
<buffersize value="20">
<lossy value="false">
<threshold value="DEBUG">
<evaluator type="log4net.Core.LevelEvaluator,log4net">
<threshold value="ERROR">
</threshold></evaluator>
<layout type="log4net.Layout.PatternLayout,log4net">
<conversionpattern value="%newline User:[%identity] %newline HostName:%property{log4net:HostName} %newline Level:%level %newlineMessage:%message %newlineLogger: %logger% %newlineEvent:%method() %newlineThread: %thread %newlineDate:%date{dd/MM/yyyy} %newlineTime:%date">
</conversionpattern></layout>
</threshold></lossy></buffersize></smtphost></subject></from></to></appender>
<root>
<appender-ref ref="SmtpAppender">
<appender-ref ref="File">
<level value="ALL">"
</level></appender-ref></appender-ref></root>
</log4net>
<appsettings>
</appsettings></configuration>  


write the Cs.File like this
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using log4net;
using log4net.Config;
using log4net.Appender;
using System.Xml.Schema;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Btn_Click(object sender, EventArgs e)
{       
try
{
int a = 10; int b = 0;
int c = a / b;
}
catch (Exception ex)
{
log4net.Config.XmlConfigurator.Configure();
ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
logger.Debug(ex.Message);
}
}
}

Powered by Blogger.