ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,jQuery Plugins,jQuery UI,SSRS,XML,HTML,jQuery demos,code snippet examples.

Breaking News

  1. Home
  2. C #
  3. Save Error Log or Exception Log in text file in C#

Save Error Log or Exception Log in text file in C#

For any standard application system it is recommended to manage automated exceptions handling system. It is done in a smart way so that the users can’t realized. This increase the applications performance and efficiency. This article describes how to write error logs in a text file in C# ? or how to write error logs in note pad in C#. Summary of the article:
  • Why we should Save Error Logs?
  • Create Log Directory
  • Create Error Log Class & Methods
  • Call Error Log Method
Why we should Save Error Logs?
The advantages of saving error logs are more. Error handling or exception handling is the most vital part of any software development. Generally we are not interested to show any type of application error to end user. Error logs are very important for collecting all types of error data generated by an application. It is more useful during an early or beta release of a product. That’s why it is better to store any kind of exceptions in one place. This can be send by email or others technology to developer. Time to time developer must analyze them and fix all the bugs without knowing clients. It will increase application performance.
There are different ways to save the application errors. It depends on developers choice. Common techniques are:
  • Save error logs in database
  • Save error logs in text file
It is better to save error logs in text file rather than database. Because text file responds much quicker then database.
Create Log Directory
At first we need to create a Log Directory or Folder in our Hard Disk where Log files will be stored. Write the following code in configuration section of config file.
  <appSettings>
    <add key="LogDirectory" value="D:\LogFiles\"/>
  </appSettings>
Here “LogFiles” is our Directory or Folder name.
Create Error Log Class & Method
Write click on Solution Explorer and include a C# Class file. Give its name as “ErrorLog”. Paste the following code in “ErrorLog” Class. It may required to add some namespaces on that class. Please add the following namespaces.
using System.Configuration;
using System.Text;
using System.IO;
Write the following C# codes in ErrorLog class.
public bool WriteErrorLog(string LogMessage)
{
    bool Status = false;
    string LogDirectory = ConfigurationManager.AppSettings["LogDirectory"].ToString();

    DateTime CurrentDateTime = DateTime.Now;
    string CurrentDateTimeString = CurrentDateTime.ToString();
    CheckCreateLogDirectory(LogDirectory);
    string logLine = BuildLogLine(CurrentDateTime, LogMessage);
    LogDirectory = (LogDirectory + "Log_" + LogFileName(DateTime.Now) + ".txt");

    lock (typeof(ErrorLog))
    {
        StreamWriter oStreamWriter = null;
        try
        {
            oStreamWriter = new StreamWriter(LogDirectory, true);
            oStreamWriter.WriteLine(logLine);
            Status = true;
        }
        catch
        {

        }
        finally
        {
            if (oStreamWriter != null)
            {
                oStreamWriter.Close();
            }
        }
    }
    return Status;
}


private bool CheckCreateLogDirectory(string LogPath)
{
    bool loggingDirectoryExists = false;
    DirectoryInfo oDirectoryInfo = new DirectoryInfo(LogPath);
    if (oDirectoryInfo.Exists)
    {
        loggingDirectoryExists = true;
    }
    else
    {
        try
        {
            Directory.CreateDirectory(LogPath);
            loggingDirectoryExists = true;
        }
        catch
        {
            // Logging failure
        }
    }
    return loggingDirectoryExists;
}
        

private string BuildLogLine(DateTime CurrentDateTime, string LogMessage)
{
    StringBuilder loglineStringBuilder = new StringBuilder();
    loglineStringBuilder.Append(LogFileEntryDateTime(CurrentDateTime));
    loglineStringBuilder.Append(" \t");
    loglineStringBuilder.Append(LogMessage);
    return loglineStringBuilder.ToString();
}
        

public string LogFileEntryDateTime(DateTime CurrentDateTime)
{
    return CurrentDateTime.ToString("dd-MM-yyyy HH:mm:ss");
}
        

private string LogFileName(DateTime CurrentDateTime)
{
    return CurrentDateTime.ToString("dd_MM_yyyy");
}
Call Error Log Method
Declare an object of “ErrorLog” Class in your page or form. Call “WriteErrorLog” method in try catch event. Sample code to call “WriteErrorLog” method is:
ErrorLog oErrorLog = new ErrorLog();
try
{
    throw new Exception();
}
catch (Exception ex)
{
    oErrorLog.WriteErrorLog(ex.ToString());
}
If any error occurred during program execution time its logs will be saved in a text file with date and time in “LogDirectory”.
Error Log in Log Directory
If we open the “LogDirectory” we will find the error log files. Open one and it will be like this:
In this way we can handle error or exception in ASP.NET C# and can save the logs in a text file. This is all about error logs in C#. Hope you have enjoyed this article.

No comments