Error logging in ASP.net

It is always very difficult to reproduce the production issue in development environment , that time lot of questions will come into our mind. WHERE, WHEN, How this issue had been occurred . To get the answer for these question we can implement Error logging in ASP.net .Here I am giving two method of error handling in asp.net using c#.

1)Log the Error in to a Text file

2)Send the error details to a specific email-ID

Log the Error in to the Text Log file

using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using context = System.Web.HttpContext;
public static string LogErrorToTextLogFile(Exception ee, string errorDetails)
{
try
{
string path = context.Current.Server.MapPath(“~/ErrorLogging/”);
// check if directory exists.
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = path + DateTime.Today.ToString(“dd-MMM-yy”) + “.log”;
// check if file exist
if (!File.Exists(path))
{
File.Create(path).Dispose();
}
// log the error
using (StreamWriter writer = File.AppendText(path))
{
writer.WriteLine(“/**********************************/”);
string error = “\r\n Log written at : ” + DateTime.Now.ToString() +
“\r\n Error occured on page : ” + context.Current.Request.Url.ToString() +
“\r\n\r\n the error is :\n” + ee.ToString();
writer.WriteLine(error);
writer.WriteLine(“/**********************************/”);
writer.Flush();
writer.Close();
}
return errorDetails;
}
catch
{
throw;
}
}



2)Send the error details to a specific emailID

using System.Web.Mail
public static bool SendErrorEmail(string to, string cc, string bcc, string subject, string body, MailPriority priority, bool isHtml)
{
try
{
using (SmtpClient smtpClient = new SmtpClient())
{
using (MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress(“yourmail@domain.com”, “Your name”);
// You can specify the host name or ipaddress of your server
smtpClient.Host = “mail.yourdomain.com”; //you can specify mail server IP address here
//Default port is 25
smtpClient.Port = 25;
NetworkCredential info = new NetworkCredential(“yourmail@domain.com”, “your password”);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = info;
//From address will be given as a MailAddress Object
message.From = from;
message.Priority = priority;
// To address collection of MailAddress
message.To.Add(to);
message.Subject = subject;
// CC and BCC optional
if (cc.Length > 0)
{
message.CC.Add(cc);
}
if (bcc.Length > 0)
{
message.Bcc.Add(bcc);
}
//Body can be Html or text format;Specify true if it is html message
message.IsBodyHtml = isHtml;
// Message body content
message.Body = body;
// Send SMTP mail
smtpClient.Send(message);
}
}
return true;
}
catch (Exception ee)
{
Logger.LogError(ee, “Error while sending email to ” + toAddress);
throw;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *