Introduction

Error handling is a critical aspect of software development, ensuring that developers can identify and address issues effectively. In C#/.NET applications, logging errors is a common practice, providing insights into system failures and helping developers debug issues efficiently. In this guide, we'll explore two popular methods for error logging in C#/.NET: using CSV files and leveraging the log4net library where we learn to create as well as update CSV files at the same time. Let's dive in!

Solution Overview

Error logging in CSV files encompasses two wildly used methods:

  1. Log4Net (2.0.15)
  2. CsvHelper (31.0.4)

1. Log4Net

The log4net library stands as a robust logging framework within the .NET ecosystem, offering advanced features for error handling. Below is a detailed exploration of leveraging log4net for error logging in C#/.NET applications for different types of files.

Step 1. Install log4net Package

Before proceeding, ensure that you have the log4net package installed in your C#/.NET project. If not, you can install it via NuGet Package Manager or using the Package Manager Console with the command: Install-Package log4net or goto Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution, and search for "Log4Net" (version 2.0.15).

Step 2. Define the LogData Method

Create a method named LogData with parameters for SPCandidateID, ErrorMessage, SPListName, SPListItemID, and DBTableName. This method will handle the logging of error data to a CSV file.

Code

public void LogData(string ID, string ErrorMessage, string Name, string DBTableName)
{
    // Define the file path
    string filePath = "error_data.csv";
    string ErrorMessageFormatted = ErrorMessage.Replace(",", "_");
    
    // Write or append data to the CSV file
    using (StreamWriter writer = System.IO.File.Exists(filePath) ? System.IO.File.AppendText(filePath) : new StreamWriter(filePath))
    {
        // If the file is newly created, write the headers
        if (writer.BaseStream.Position == 0)
        {
            writer.WriteLine("ID,ErrorMessage,Name,DBTableName");
            Console.WriteLine("New file created");
        }

        // Write the rows with the provided values
        writer.WriteLine($"{ID},{ErrorMessage},{Name},{DBTableName}");
    }

    Console.WriteLine($"CSV file '{filePath}' has been updated or created.");
}

Step 3. Define File Path and Process Error Message

Step 4. Open or Create the CSV File

Step 5. Write Headers if File is Newly Created

Step 6. Write Error Data to CSV

Step 7. Display Confirmation Message

Code

try
{
    // Your code that might throw an exception
}
catch (Exception ex)
{
    // Log the error using LogData method
    LogData("1", ex.Message, "Main", "error_table");

    // Handle the exception or perform additional logging/reporting
    Console.WriteLine("An error occurred: " + ex.Message);
}

2. CsvHelper

Utilizing the CSV NuGet package provides a convenient and efficient means of logging errors in C#/.NET applications. Here's a step-by-step breakdown.

Step 1. Install CsvHelper NuGet Package

Step 2. Define the csvGenerator Method

Code

public void csvGenerator(string ID, string ErrorMessage, string Name, string DBTableName)
{
    // Define the file path
    string filePath = "error_data.csv";

    // Write or append data to the CSV file
    using (StreamWriter writer = System.IO.File.Exists(filePath) ? System.IO.File.AppendText(filePath) : new StreamWriter(filePath))
    {
        // If the file is newly created, write the headers
        if (writer.BaseStream.Position == 0)
        {
            // Write column headers
            writer.WriteLine("ID,ErrorMessage,Name,DBTableName");
        }

        // Write the rows with the provided values
        writer.WriteLine($"{ID},{ErrorMessage},{Name},{DBTableName}");
    }

    // Confirm file update or creation
    Console.WriteLine($"CSV file '{filePath}' has been updated or created.");
}

Step 3. Define File Path

Step 4. Open or Create the CSV File

Step 5. Write Headers if File is Newly Created

Step 6. Write Error Data to CSV

Step 7. Display Confirmation Message

Code

try
{
    // Your code that might throw an exception
}
catch (Exception ex)
{
    // Log the error using LogData method
    csvGenerator("1", ex.Message, "Main", "error_table");

    // Handle the exception or perform additional logging/reporting
    Console.WriteLine("An error occurred: " + ex.Message);
}

Conclusion

Both CSV files and log4net offer effective solutions for error logging in C#/.NET applications, each with its own set of advantages and considerations. CSV files provide simplicity and ease of implementation, making them suitable for smaller projects or scenarios where external dependencies are limited. On the other hand, log4net offers advanced features such as configurable logging levels, log rotation, and centralized logging, making it ideal for larger and more complex applications. Choose the method that best fits your project requirements and implement it following the guidelines provided in this blog. Happy blogging!