In this example we will see how to save log file if we got
any error in our application. We have to save text file if got any error.
HTML CODE:
<div>
<asp:Button ID="Button1" Text="Click" runat="server" OnClick="RaiseException" Height="44px"
Width="147px" />
</div>
CODE BEHIND:
protected void RaiseException(object
sender, EventArgs e)
{
try
{
int
i = int.Parse("Umesh");
}
catch
(Exception ex)
{
this.LogError(ex);
}
}
private
void LogError(Exception
ex)
{
string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy
hh:mm:ss tt"));
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
message += string.Format("Message: {0}", ex.Message);
message += string.Format("StackTrace: {0}", ex.StackTrace);
message += Environment.NewLine;
message += string.Format("Source: {0}", ex.Source);
message += Environment.NewLine;
message += string.Format("TargetSite: {0}",
ex.TargetSite.ToString());
message += Environment.NewLine;
message += "-----------------------------------------------------------";
message += Environment.NewLine;
string
path = Server.MapPath("~/ErrorLog/ErrorLog.txt");
using
(StreamWriter writer = new StreamWriter(path,
true))
{
writer.WriteLine(message);
writer.Close();
}
}
Create Folder in your
Web application and create text file or else read my blog “How to Create Text
file dynamically in Asp.Net” and Save it ErrorLog.txt for maintain History in
text file.
Now Set any error and
see your Text file for storing error log.
Thanks for comments.....