Click here to Skip to main content
6,629,885 members and growing! (20,425 online)
Email Password   helpLost your password?
Web Development » Trace and Logs » Trace / Logs     Beginner

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

By Ali Ahmad H

An article on generating text based error log files
C#, .NET, Win2K, WinXP, ASP.NET, Visual Studio, Dev
Posted:27 May 2002
Views:240,813
Bookmarked:69 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
27 votes for this article.
Popularity: 5.56 Rating: 3.88 out of 5
1 vote, 4.3%
1
2 votes, 8.7%
2
2 votes, 8.7%
3
7 votes, 30.4%
4
11 votes, 47.8%
5

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. :-) 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

About the Author

Ali Ahmad H


Member
Was born at Subang - West Java, Indonesia. Like all IT related information include programming and networking. Can be emailed at ali(at)aliahmad.net.
Occupation: Web Developer
Company: aliahmad.net
Location: Indonesia Indonesia

Other popular Trace and Logs articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 19 of 19 (Total in Forum: 19) (Refresh)FirstPrevNext
GeneralThanks! PinmemberPraveen Modi11:30 3 Apr '09  
GeneralRe: Thanks! PinmemberAli Ahmad H18:29 5 Apr '09  
GeneralSmall enhancement - DirectoryNotFoundException Pinmemberjsytniak22:04 27 Apr '07  
Generalin case of multiple users PinmemberVishalSharmaDev0:36 6 Oct '06  
GeneralERROR LOG PinmemberRASHMIREKHA20:23 29 Mar '06  
GeneralERROR LOG PinmemberRASHMIREKHA20:21 29 Mar '06  
QuestionEvent Log Security Exception PinmemberAanchal Naidu15:33 16 Dec '05  
Generalsimple messege board PinsussAnonymous20:47 2 Oct '05  
GeneralRe: simple messege board PinsussAnonymous21:48 5 Oct '05  
GeneralLog all activities performed in my web app. Pinmemberchandler sue6:10 4 Jun '04  
GeneralRe: Log all activities performed in my web app. PinsussAnonymous16:19 21 Jun '04  
GeneralRe: Log all activities performed in my web app. PinmemberSanjay Ananth19:58 12 Jul '05  
GeneralError Message PinmemberPrashant Agrawal21:25 15 Apr '04  
GeneralRe: Error Message PinmemberPraphulla3:02 23 Dec '04  
GeneralRe: Error Message PinmemberAli Ahmad H13:47 23 Dec '04  
GeneralRe: Error Message PinmemberPraphulla20:22 23 Dec '04  
GeneralSyncronization problems Pinmemberjavier_glez_carpio6:42 24 Mar '03  
GeneralRe: Syncronization problems PinmemberRayLouw2:45 10 Apr '06  
GeneralInteresting.... PinmemberSteve McLenithan13:03 4 Oct '02  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 27 May 2002
Editor: Paul Watson
Copyright 2002 by Ali Ahmad H
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project