Error Log Creation Using C# In Asp.Net
So for this first we will create a new asp.net web applicationand add a new page. Now add new class file and add the below code in this class file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace LogCreator
{
public class LogManager
{
public static string PathToCreateLog = System.Configuration.ConfigurationSettings.AppSettings["logpath"].ToString();
public static void CreateLogFile(string Message)
{
FileInfo fi;
FileStream fstr;
//Check whether dir exists or not if not then create it
#region Try to create the directory. if not extits
if (!System.IO.Directory.Exists(PathToCreateLog))
{
System.IO.DirectoryInfo di = System.IO.Directory.CreateDirectory(PathToCreateLog);
}
#endregion
string strCurrentDate = DateTime.Now.ToString("yyyyMMdd");
string strFileName = strCurrentDate + "_Log.txt";
//Create New File if not exists
if (!System.IO.File.Exists(PathToCreateLog + strFileName))
{
fi = new FileInfo(PathToCreateLog + strFileName);
fstr = fi.Create();
}
//Write the text to the file
try
{
StreamWriter strWriteText = new StreamWriter(PathToCreateLog + strFileName, true);
try
{
strWriteText.WriteLine("`" + DateTime.Now.ToString() + " `, `" + Message + " `");
}
catch (Exception ex)
{
}
finally
{
strWriteText.Dispose();
strWriteText.Close();
}
}
catch (Exception ex1)
{
}
finally
{
}
}
}
}
In above code i have defined the path in which folder and log text file will get created. In above code log file will get created by date.
<add key="logpath" value="C:\LogFiles\"/>
You can change the path.
Now come to your .aspx page in this page add a text box and button. on button click add the below code.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Enter Number and Click"
onclick="Button1_Click" />
C#
protected void Button1_Click(object sender, EventArgs e)
{
try
{
int value = Convert.ToInt32(TextBox1.Text);
}
catch (Exception ex)
{
LogManager.CreateLogFile(ex.Message.ToString());
}
Now run the page and before that add a new break point.
now add some text and press button.
As you reach break point you will get error.
Now stop debug . Now check the log path which you have defined. and open the text file.
____________________
____________________
|
Monday, 4 March 2013
Error Log Creation Using C# In Asp.Net
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment