Sometimes you might have the requirement to create log file while writing code either in Plugin or Custom Workflow or in web service etc to trace and keep the generated error.There might be a other option as well to keep it but here i am going to show Error Log in Text file.
In this blog I have described how to create log file in C#. Log file can be simple text file, XML document or we can also use tables in database to create log. Here I have used.txt file. In this file we have stored information about generated exception of application. Using this log file we have easily find out error list. In this file we have stored information according our requirement. For example in log file we have stored file name, exception name, date and time, error line number, event name, Controls name etc.
In this blog I have described how to create log file in C#. Log file can be simple text file, XML document or we can also use tables in database to create log. Here I have used.txt file. In this file we have stored information about generated exception of application. Using this log file we have easily find out error list. In this file we have stored information according our requirement. For example in log file we have stored file name, exception name, date and time, error line number, event name, Controls name etc.
Now let’s to implementation
using System;
using System.IO;
using context = System.Web.HttpContext;
namespace LogText
{
public class Logger
{
public Logger(string ErrorCode, string ErrorMsg)
{
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 now
using (StreamWriter writer = File.AppendText(path))
{
string error = "\r\nLog written at : " + DateTime.Now.ToString() +
"\r\n\r\nError occured on page : " + context.Current.Request.Url.ToString() +
"\r\n\r\nError Code : " + ErrorCode +
"\r\n\r\nError Message : " + ErrorMsg;
writer.WriteLine(error);
writer.WriteLine("=======================================");
writer.Flush();
writer.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
Where i would see the Error Log Text file ?
A folder will be created inside your Project/Solution named 'ErrorLogging'. All error log test file will be created inside this Folder with named as 'Log Creation Date.log' for example- '04-Jul-13.log'.
Error Log File will look like as below:
Error Log File will look like as below: