Create Custom Error Log files in Asp.net using C#

Introduction:
This article explains how to create error log files in asp.net using c#. To generate log files in asp.net we need to get that errors in catch block and store it in folder or local drive in txt format or other format in asp.net using c#.

To create error log files in asp.net first create one new folder "logfiles" in your application then  open your aspx page and write the following code

Aspx Page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Create Log Files in Asp.net using c#, vb.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnLog" runat="server" Text="Generate Log" onclick="btnLog_Click" />
</div>
</form>
</body>
</html>

C# Code:

using System;
using System.Web;
using System.Data.SqlClient;
using System.IO;
using System.Data;


 protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLog_Click(object sender, EventArgs e)
{
try {
DataTable dt=new DataTable();
SqlConnection con = new SqlConnection("Data Source=vepsh;
Integrated Security=true;Initial Catalog=MySampleDB");

SqlCommand cmd = new SqlCommand("crudoperations", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@status", "SELECT");
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
catch(Exception ex){
logerrors(ex.Message);
lblresult.Text = "Error occured please check complete details in log file";
}
}
public void logerrors(string error)
{
string pageName = Path.GetFileName(Request.Path);
string filename = "Log_" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt";
string filepath = Server.MapPath("~/logfiles/" + filename);
if (File.Exists(filepath))
{
using (StreamWriter stwriter = new StreamWriter(filepath, true))
{
stwriter.WriteLine("-------------------START-------------" + DateTime.Now);
stwriter.WriteLine("Page :" + pageName);
stwriter.WriteLine(error);
stwriter.WriteLine("-------------------END-------------" + DateTime.Now);
}
}
else
{
StreamWriter stwriter = File.CreateText(filepath);
stwriter.WriteLine("-------------------START-------------" + DateTime.Now);
stwriter.WriteLine("Page :" + pageName);
stwriter.WriteLine(error);
stwriter.WriteLine("-------------------END-------------" + DateTime.Now);
stwriter.Close();
}
}

Now open your log file in "logfiles" folder that would be like as following  

error log



Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment