Click here to Skip to main content
11,495,534 members (64,280 online)
Click here to Skip to main content

Create Simple Error Log Files using ASP.NET and C#

, 27 May 2002 510.2K 10.2K 96
Rate this:
Please Sign up or sign in to vote.
An article on generating text based error log files

Sample Image

Picture 1. Sample error message

Sample Image

Picture 2. Sample error log file

Overview

This article demonstrates how to create a simple text based log file to log error messages with your own format using a C# class. Based on your needs, this class can modified and edited to create other log files, such as user activity log, user login time log, etc.

This class demonstrates the use of following namespaces:

  • System.IO
  • System.Text

The namespaces contain methods to create files in directories.

Installation Step

If you have downloaded the source code, you can follow these steps to install the project. You can then build and debug the code with VS.NET.

  1. Unzip the project source to \inetpub\wwwroot\CreateLogFiles directory
  2. Give the Logs directory -in the CreateLogFiles directory- full access permission, log files will be created in this directory
  3. Create new CreateLogFiles virtual site using your IIS MMC snap in, or Internet Services Manager
  4. If you are not using CreateLogFiles virtual site, edit the file CreateLogFiles.csproj.webinfo and set the URLPath to your virtual site name
  5. Double click CreateLogFiles.csproj with VS.NET and build the project to get the dll file in the bin directory
  6. Open your browser, browse to your project using http, in this case: http://localhost/CreateLogFiles/CreateLogFiles.aspx
  7. Try to fill the TextBox, if you have an error, you can see the errorlog was created in the Logs directory

Source Code

In this project, the main idea is to create a class, CreateLogFiles, that will create files in a specific directory from the web. This class uses two namespaces:

using System.IO;
using System.Text;

Before we make a function to create an error files, we have to declare some variables that will be used in our function. This is an example of variable declaration:

private string sLogFormat;
private string sErrorTime;

public CreateLogFiles()
{
    //sLogFormat used to create log files format :
    // dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message
    sLogFormat = DateTime.Now.ToShortDateString().ToString()+" "+DateTime.Now.ToLongTimeString().ToString()+" ==> ";
            
    //this variable used to create log filename format "
    //for example filename : ErrorLogYYYYMMDD
    string sYear    = DateTime.Now.Year.ToString();
    string sMonth    = DateTime.Now.Month.ToString();
    string sDay    = DateTime.Now.Day.ToString();
    sErrorTime = sYear+sMonth+sDay;
}

and this is a function that will create error files. Please modify this function for your needs, or you can make other functions to create other log files :

public void ErrorLog(string sPathName, string sErrMsg)
{
    StreamWriter sw = new StreamWriter(sPathName+sErrorTime,true);
    sw.WriteLine(sLogFormat + sErrMsg);
    sw.Flush();
    sw.Close();
}

To use this class, I create an example web form called: CreateLogFiles. A snapshot of this web form is shown above, picture 1. This is used to search a file in our directory. If the file exists, then no error log file is created, but when a file doesn't exist, it will create an error log file with the specific error message.

This is the code behind for this page. I call the ErrorLog function from our class when the Search button is clicked.

private void BtnFind_Click(object sender, System.EventArgs e)
{
    try
    {
        StreamReader sr = new StreamReader(this.TxtFilename.Text);
        sr.Read();
        sr.Close();
        Msg.Visible = true;
        Msg.Text = "File "+ this.TxtFilename.Text +" was found";
    }
    catch(Exception ex)
    {
        CreateLogFiles Err = new CreateLogFiles();
        Err.ErrorLog(Server.MapPath("Logs/ErrorLog"),ex.Message);
        Msg.Visible = true;
        Msg.Text = "Fatal error : "+ ex.Message + ", please find a complete error at ErrorLog file";
    }
}

I am using try and catch to check automatically whether file exists or not. An error message gets automatically by the Exception method.

That's it. Smile | :) You can view complete source code in the download file.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Ali Ahmad H
Web Developer AliAhmadH
Indonesia Indonesia
Was born at Subang - West Java, Indonesia. Like all IT related information include programming and networking. Can be emailed at ali(at)aliahmadh.com

Comments and Discussions

 
GeneralMy vote of 1 Pin
joginder-banger15-Jan-15 1:04
professionaljoginder-banger15-Jan-15 1:04 
QuestionNice article. Could this be done in VB? Pin
sudevsu8-Jan-15 5:06
groupsudevsu8-Jan-15 5:06 
GeneralMy vote of 1 Pin
Akhil Mittal3-Jul-14 23:55
mvpAkhil Mittal3-Jul-14 23:55 
QuestionThanks Pin
BBBwex16-May-14 6:09
memberBBBwex16-May-14 6:09 
GeneralMy vote of 1 Pin
fermanakgun3-Mar-14 4:02
memberfermanakgun3-Mar-14 4:02 
QuestionNice Pin
Ganapathy A27-Aug-13 19:35
memberGanapathy A27-Aug-13 19:35 
Questionthanks good Pin
rose lindo23-Apr-13 22:27
memberrose lindo23-Apr-13 22:27 
GeneralMy vote of 2 Pin
hims05627-Nov-12 2:11
memberhims05627-Nov-12 2:11 
GeneralThanks for Article Pin
Rajeshkumar Chavada8-Aug-12 2:20
memberRajeshkumar Chavada8-Aug-12 2:20 
Questionconversion problem Pin
viji@sampathraj13-Dec-11 21:08
memberviji@sampathraj13-Dec-11 21:08 
SuggestionPlease wrap disposable resources (StreamWriter & Reader) in using( ) blocks Pin
Damon Overboe26-Oct-11 5:39
memberDamon Overboe26-Oct-11 5:39 
GeneralRe: Please wrap disposable resources (StreamWriter & Reader) in using( ) blocks Pin
Ashok A23-Apr-12 14:31
memberAshok A23-Apr-12 14:31 
QuestionThank you! Pin
krembf5-Sep-11 12:33
memberkrembf5-Sep-11 12:33 
Questionneed help to access Pin
madhri1-Aug-11 3:22
membermadhri1-Aug-11 3:22 
AnswerRe: need help to access Pin
Ali Ahmad H1-Aug-11 17:41
memberAli Ahmad H1-Aug-11 17:41 
GeneralThanks Pin
Lubna_0419-Apr-10 17:21
memberLubna_0419-Apr-10 17:21 
GeneralThanks! Pin
Praveen Modi3-Apr-09 11:30
memberPraveen Modi3-Apr-09 11:30 
GeneralRe: Thanks! Pin
Ali Ahmad H5-Apr-09 18:29
memberAli Ahmad H5-Apr-09 18:29 
GeneralSmall enhancement - DirectoryNotFoundException Pin
jsytniak27-Apr-07 22:04
memberjsytniak27-Apr-07 22:04 
Generalin case of multiple users Pin
VishalSharmaDev6-Oct-06 0:36
memberVishalSharmaDev6-Oct-06 0:36 
hi dear

i need to create a log file for each and every request made to my application. now can u please tell me how can i do this with the help of this code.

also, please tell me that, if i, made this class and its methods static then what would be the expectations after doing that.

different log file should be written for each & every request.

please help in the matter.

a positive reponse is expected from all guys



Thanks & Regards

Vishal Sharma
vishalsharma556@yahoo.co.in

GeneralERROR LOG Pin
RASHMIREKHA29-Mar-06 20:23
memberRASHMIREKHA29-Mar-06 20:23 
GeneralERROR LOG Pin
RASHMIREKHA29-Mar-06 20:21
memberRASHMIREKHA29-Mar-06 20:21 
QuestionEvent Log Security Exception Pin
Aanchal Naidu16-Dec-05 15:33
memberAanchal Naidu16-Dec-05 15:33 
Generalsimple messege board Pin
Anonymous2-Oct-05 20:47
sussAnonymous2-Oct-05 20:47 
GeneralRe: simple messege board Pin
Anonymous5-Oct-05 21:48
sussAnonymous5-Oct-05 21:48 
GeneralLog all activities performed in my web app. Pin
chandler sue4-Jun-04 6:10
memberchandler sue4-Jun-04 6:10 
GeneralRe: Log all activities performed in my web app. Pin
Anonymous21-Jun-04 16:19
sussAnonymous21-Jun-04 16:19 
GeneralRe: Log all activities performed in my web app. Pin
Sanjay Ananth12-Jul-05 19:58
memberSanjay Ananth12-Jul-05 19:58 
GeneralError Message Pin
Prashant Agrawal15-Apr-04 21:25
memberPrashant Agrawal15-Apr-04 21:25 
GeneralRe: Error Message Pin
Praphulla23-Dec-04 3:02
memberPraphulla23-Dec-04 3:02 
GeneralRe: Error Message Pin
Ali Ahmad H23-Dec-04 13:47
memberAli Ahmad H23-Dec-04 13:47 
GeneralRe: Error Message Pin
Praphulla23-Dec-04 20:22
memberPraphulla23-Dec-04 20:22 
GeneralSyncronization problems Pin
javier_glez_carpio24-Mar-03 6:42
memberjavier_glez_carpio24-Mar-03 6:42 
GeneralRe: Syncronization problems Pin
RayLouw10-Apr-06 2:45
memberRayLouw10-Apr-06 2:45 
GeneralInteresting.... Pin
Steve McLenithan4-Oct-02 13:03
memberSteve McLenithan4-Oct-02 13:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 28 May 2002
Article Copyright 2002 by Ali Ahmad H
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid