You are on page 1of 6

8/9/2017 Save Error Log or Exception Log in text file in C# | Cybarlab

Cybarlab
Home Programming Framework Database Scripting HTML/CSS

Services Reporting Interview All Post

19 Mar 2013
Search this site...

Home ASP.NET C# Save Error Log or Exception Log in text file Search
in C#

Save Error Log or Exception


Popular Posts Recent Posts

CRUD operations in

Log in text le in C# AngularJS and Web API

HTML5 Local Storage and


Posted in ASP.NET, C# By Rashed On March 19, 2013
Session Storage

For any standard application system it is recommended to manage


automated exceptions handling system. It is done in a smart way so that Find us
the users cant realized. This increase the applications performance and
efficiency. This article describes how to write error logs in a text file in Cybarlab.com
C# ? or how to write error logs in note pad in C#. Summary of the 292 likes

article:

Why we should Save Error Logs? Like Page


Create Log Directory
Create Error Log Class & Methods Be the first of your friends to like this
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. Thats 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:

http://cybarlab.com/save-error-log-in-text-file-in-c-sharp 1/6
8/9/2017 Save Error Log or Exception Log in text file in C# | Cybarlab

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
{

http://cybarlab.com/save-error-log-in-text-file-in-c-sharp 2/6
8/9/2017 Save Error Log or Exception Log in text file in C# | Cybarlab

}
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");
}
http://cybarlab.com/save-error-log-in-text-file-in-c-sharp 3/6
8/9/2017 Save Error Log or Exception Log in text file in C# | Cybarlab

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.

Related Posts

Send E-mail using C IP Address in C#? Exception Handling in


Sharp C#

Comments

By Syed Ayaz

http://cybarlab.com/save-error-log-in-text-file-in-c-sharp 4/6
8/9/2017 Save Error Log or Exception Log in text file in C# | Cybarlab

please help me where i initialize the class an d how my


desktop application create log file is it automatically
create?
on July 20, 2013 Reply

By Rashed
Syed Ayaz,
It will work for both desktop or web application.
on November 17, 2013 Reply

By dinesh
Code is not working
on November 14, 2013 Reply

By Rashed
Dineh,
Can your check now. I think it will work now.
Thanks for comments.
on November 17, 2013 Reply

By Vijayalakshmi
Thank you very much for this post. It is really helpful.
God Bless You with Good Health, Long Life, Properity,
Happiness, Wisodm and Peace.
on August 29, 2014 Reply

By Vijayalakshmi
Thank you very much for this post. It is really helpful.
God Bless You with Good Health, Long Life, Prosperity,
Happiness, Wisdom and Peace.
on August 29, 2014 Reply

By Srj
Thanks for the post. Great work amigo. Code works like
a charm
on October 20, 2014 Reply

Leave a Reply

Comment

http://cybarlab.com/save-error-log-in-text-file-in-c-sharp 5/6
8/9/2017 Save Error Log or Exception Log in text file in C# | Cybarlab

Name

Email

Website

Post Comment

C# API

ASP.NET Interview

ASP.NET MVC Mobile

Entity Framework Visual Studio

Software Engineering See more..

About

Contact

Sitemap

Terms of Use

Privacy Policy

Cybarlab Copyright 2017. Back to Top

http://cybarlab.com/save-error-log-in-text-file-in-c-sharp 6/6

You might also like