Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to log errors into a text file in ASP.NET

Author: Richard Wand
Download Source Code : 1350_LogErrorsInTextFile.zip

This article will explain how we can write error messages in a text file in ASP.NET.

 

We can log every exception in a text file but it will really slow our application if the application is big. Error logging in a text file mechanism can be used for small applications. Writing error messages is same as we write any other text file by using classes in System.IO namespace. We will write a function and use StreamWriter class to write error message to a text file.

 

  1. Create new website in Visual Studio 2010
  2. Add two textboxes, a Button and two Labels in aspx page of a web form

    <h4>Provide two values for divison:</h4>
    <asp:TextBox ID="txtbox1" runat="server"></asp:TextBox>
    <asp:TextBox ID="txtbox2" runat="server"></asp:TextBox>
    <br />
    <asp:Button ID="btnResult" runat="server" Text="Result"
        onclick="btnResult_Click" />
    <br />
    <asp:Label ID="lblResult" runat="server" ></asp:Label>
    <br />
    <asp:Label ID="lblMessage" runat="server" ></asp:Label>
     
  3. Add a text file in your website and rename it as ErrorLog.txt
     
  4. We have to use following namespace in our code

    C#
     
    using System.IO;
     
    VB.NET
     
    Imports System.IO
     
  5. Add a function and write code below in that function

    C#
     
    public static void LogErrorIntoTextFile(Exception ex, string method)
    {
        try
        {
            string filePath = HttpContext.Current.Server.MapPath("ErrorLog.txt");
     
            if (File.Exists(filePath))
            {
                StreamWriter writer = new StreamWriter(filePath, true);
     
                string logMessage = "Error time: " + DateTime.Now.ToString() + "\n";
                logMessage += "Error Page: " + HttpContext.Current.Request.Url.ToString() + "\n";
                logMessage += "Error method: " + method + "\n";
                logMessage += "Error Message: " + ex.Message.ToString() + "\n";
                writer.WriteLine(logMessage);
                writer.Flush();
                writer.Close();
            }
        }
        catch (Exception e)
        {
     
        }
    }
     
    VB.NET
     
    Public Shared Sub LogErrorIntoTextFile(ByVal ex As Exception, ByVal method As String)
        Try
            Dim filePath As String = HttpContext.Current.Server.MapPath("ErrorLog.txt")
     
            If File.Exists(filePath) Then
                Dim writer As New StreamWriter(filePath, True)
     
                Dim logMessage As String = "Error time: " & DateTime.Now.ToString() & vbLf
                logMessage += "Error Page: " & HttpContext.Current.Request.Url.ToString() & vbLf
                logMessage += "Error method: " & method & vbLf
                logMessage += "Error Message: " & ex.Message.ToString() & vbLf
                writer.WriteLine(logMessage)
                writer.Flush()
                writer.Close()
            End If
     
        Catch e As Exception
        End Try
    End Sub
     
    Get the path of the file first and then check if file exists.  Create an instance of StreamWriter class. Set the append parameter if StreamWriter constructor to true. StreamWriter class constructor initializes a new instance for specified file name of path with append option and if the file is not there, it will create a new file at the specified path. You can write time when error is written to file, the URL of the page and method name where error is generated and the actual error.
     
  6. Now add button click event and write code below in it

    C#
     
    protected void btnResult_Click(object sender, EventArgs e)
    {
        try
        {
            int a = Convert.ToInt32(txtbox1.Text);
            int b = Convert.ToInt32(txtbox2.Text);
            int c = a / b;
     
            lblResult.Text = c.ToString();        
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message.ToString();
            LogErrorIntoTextFile(ex, "btnResult_Click()");
        }
    }
     
    VB.NET
     
    Protected Sub btnResult_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnResult.Click
        Try
            Dim a As Integer = Convert.ToInt32(txtbox1.Text)
            Dim b As Integer = Convert.ToInt32(txtbox2.Text)
            Dim c As Integer = a \ b
     
            lblResult.Text = c.ToString()
     
        Catch ex As Exception
            lblMessage.Text = ex.Message.ToString()
            LogErrorIntoTextFile(ex, "btnResult_Click()")
        End Try
    End Sub
     
    Here perform a simple division operation in try block to check exceptions and call our function in catch block.
     
  7. Now start debugging.

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to display XML file data in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net