.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Log Error or Exception in a Text File

Posted By:Pankaj Mishra       Posted Date: February 13, 2009    Points: 25    Category: C#    URL: http://www.dotnetspark.com  
 

Log Error or exception in a Text File is simple in .NET. Logically its something writing in a text file and we know that .NET provides few classes to manipulate text file. These classes are available in System.IO namespace.

You  can also use Log4Net to log error or exception in xml file for more details refer this article

http://www.dotnetspark.com/kb/249-log-error-exception-using-log4net.aspx

We will see step by step Approach to log Error or exception in a text (.txt) file.

We are using StreamWriter to create and write Log file

Step 1 : Lets see the method which will write to text file

C# code

public static void WriteLogFile(string fileName, string methodName, string message)

{

try
{

if (!string.IsNullOrEmpty(message))

{

using (FileStream file = new FileStream(Application.StartupPath + "\\Log.txt", FileMode.OpenOrCreate, FileAccess.Write))

{

StreamWriter streamWriter = new StreamWriter(file);

streamWriter.WriteLine((((System.DateTime.Now + " - ") + fileName + " - ") + methodName + " - ") + message);

streamWriter.Close();

}

}

}

catch

{

}

}

VB .NET code

	Public Shared Sub WriteLogFile(ByVal fileName As String, ByVal methodName As String, ByVal message As String) 
    Try
        If message <> "" Then
            Using file As New FileStream(Application.StartupPath & "\Log.txt", FileMode.OpenOrCreate, FileAccess.Write)
                Dim streamWriter As New StreamWriter(file)
                streamWriter.WriteLine((((System.DateTime.Now & " - ") + fileName & " - ") + methodName & " - ") + message)
                streamWriter.Close()
            End Using
        End If
    Catch
    End Try
End Sub


Step 2 : Now lets test the above function

On Button click we wrote this line to produce exception

private void button1_Click(object sender, EventArgs e)

{

try

{

int a = 10, b = 0;

int result = a / b; //runtime Exception will throw

}

catch (Exception ex)

{

WriteLogFile(this.GetType().Name, "button1_Click()", ex.Message.ToString());

}

}

Step 3 : and now lets examine the Log.txt file in the root folder folder


 

Hope this will help beginner  to log error or exception in a text file

Cheers
Pankaj!!!


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend