Introduction :
Hi, Here I will Explain you how to create the Log File for the Errors that have created in Runtime inWeb Application. Here you need to create the Folder where you are going to place a Error Log as a Text File. I have created a Folder Named 'Log' and TextFile Named 'LogFile.txt'. I used Exception Handling Concept to Catch errors, in Catch block i will write the Error TextFile with the time of the Error Raised.
Note: My code in the Try block will throw a Runtime Error, this code written to write the Error in ErrorLog file.
Aspx Code :
<html>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:center">
<br />
<asp:TextBox ID="TextBox1"
runat="server"></asp:TextBox>
<asp:Button ID="Button1"
runat="server"
Text="Click
Here"
onclick="Button1_Click"
/><br/>
<asp:Label ID="lblStatus"
runat="server"
ForeColor="Red"></asp:Label>
</div>
</form>
</body>
</html>
Code Behind ( C# ) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace Errorlog
{
public partial class Page1 :
System.Web.UI.Page
{
protected void
Button1_Click(object sender, EventArgs e)
{
try
{
string i;
i = TextBox1.Text;
DateTime ds = Convert.ToDateTime(i);
}
catch (Exception
es)
{
if (File.Exists(Server.MapPath("Log\\LogFile.txt")) == false)
{
File.Create(Server.MapPath("Log\\LogFile.txt")).Dispose();
}
TextWriter writer = new StreamWriter(Server.MapPath("Log\\LogFile.txt"), true);
writer.WriteLine("");
writer.WriteLine("________________"
+ DateTime.Now.ToString() + "___________");
writer.WriteLine(es.Message);
writer.WriteLine("");
writer.Flush();
writer.Close();
lblStatus.Text = es.Message;
}
}
}
}