Create log files to handle the exceptions using log4net.dll to track entire application

Exception Handling Using Log4net dll
  1. first you need to download the log4net dll add then click add reference to your project
  2. Add the below lines to your web.config file
    <configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>

Then add the below lines to below the configsection block in web.config file

<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="file" value="Logs\\logfile" />
<param name="appendToFile" value="true" />
<param name="rollingStyle" value="Date" />
<param name="StaticLogFileName" value="false"/>
<param name="datePattern" value="yyyyMMdd.\tx\t" />
<layout type="log4net.Layout.PatternLayout">
<param name="conversionPattern" value="%date{yyyy-MM-dd HH:mm:ss-fff} %-5level: [%logger] %message%newline" />
</layout>
</appender>
<root>
<level value="All" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>

Add few lines of code to Global.asax.cs file

public class Global : HttpApplication
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
Log.Info("Application Started");
}

protected void Session_Start(object sender, EventArgs e)
{
}

protected void Application_BeginRequest(object sender, EventArgs e)
{
}

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}

protected void Application_Error(object sender, EventArgs e)
{
var ctx = HttpContext.Current;
var exception = Server.GetLastError();

if (exception == null || exception.Message == "File does not exist.")
return;

var errorInfo = string.Format("Offending URL: {0}\r\n Session: {5}\r\n Source: {1}\r\n Message: {2}\r\n Detail Message: {3}\r\n Stack trace: {4}",
ctx.Request.Url,
exception.Source,
exception.Message,
exception.InnerException.Message,
exception.StackTrace,
ctx.Session.SessionID);

Log.Error(errorInfo);
Session["ErrorInfo"] = errorInfo;
}

protected void Session_End(object sender, EventArgs e)
{
}

protected void Application_End(object sender, EventArgs e)
{
Log.Info("Application Closed");
}
}

Now create one page default.aspx in that code behind file

Add two namespace at the top of the page

using log4net;
using System.Reflection;


public partial class _Default : System.Web.UI.Page
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
Log.Error("No Error");
}
catch (Exception ex)
{
Log.Error("Error");
}
finally
{
}
}

}
}



0 comments:

Post a Comment

Vikram Chandra Theme by BloggerThemes & NewWPThemes Sponsored by iBlogtoBlog