Create Dynamic Error Based Log Information

To create dynamic error-based log information in .NET and store it in a database table, you can follow these steps.

Create a Log Table in the Database

First, set up a table in your database to store log information. Here's an example of what the table might look like,

CREATE TABLE ErrorLogs (
    LogId INT PRIMARY KEY IDENTITY,
    LogDate DATETIME NOT NULL,
    LogLevel VARCHAR(50) NOT NULL,
    Message NVARCHAR(MAX) NOT NULL,
    StackTrace NVARCHAR(MAX),
    Source NVARCHAR(255),
    UserId NVARCHAR(50),
    AdditionalInfo NVARCHAR(MAX)
);

Create a Logging Class in .NET

Create a class to handle the logging of errors to the database. This class will include methods to log different levels of information (e.g., errors, warnings, info).

using System;
using System.Data.SqlClient;
using System.Configuration;

public static class Logger
{
    private static readonly string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionStringName"].ConnectionString;

    public static void LogError(Exception ex, string userId = null, string additionalInfo = null)
    {
        Log("Error", ex.Message, ex.StackTrace, ex.Source, userId, additionalInfo);
    }

    public static void LogWarning(string message, string userId = null, string additionalInfo = null)
    {
        Log("Warning", message, null, null, userId, additionalInfo);
    }

    public static void LogInfo(string message, string userId = null, string additionalInfo = null)
    {
        Log("Info", message, null, null, userId, additionalInfo);
    }

    private static void Log(string logLevel, string message, string stackTrace, string source, string userId, string additionalInfo)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                string query = @"
                    INSERT INTO ErrorLogs (LogDate, LogLevel, Message, StackTrace, Source, UserId, AdditionalInfo)
                    VALUES (@LogDate, @LogLevel, @Message, @StackTrace, @Source, @UserId, @AdditionalInfo)";

                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    cmd.Parameters.AddWithValue("@LogDate", DateTime.Now);
                    cmd.Parameters.AddWithValue("@LogLevel", logLevel);
                    cmd.Parameters.AddWithValue("@Message", message);
                    cmd.Parameters.AddWithValue("@StackTrace", (object)stackTrace ?? DBNull.Value);
                    cmd.Parameters.AddWithValue("@Source", (object)source ?? DBNull.Value);
                    cmd.Parameters.AddWithValue("@UserId", (object)userId ?? DBNull.Value);
                    cmd.Parameters.AddWithValue("@AdditionalInfo", (object)additionalInfo ?? DBNull.Value);

                    cmd.ExecuteNonQuery();
                }
            }
        }
        catch (Exception e)
        {
            // Handle any exceptions that occur while trying to log the error (e.g., send an email, write to a file, etc.)
            Console.WriteLine("Logging failed: " + e.Message);
        }
    }
}

Log Errors in Your Application

You can now use this Logger class to log errors whenever they occur in your application.

try
{
    // Your code that might throw an exception
}
catch (Exception ex)
{
    Logger.LogError(ex, userId: "CurrentUserId", additionalInfo: "Additional context if needed");
}

Configuration (Optional)

Make sure you have a connection string in your Web.config or App.config file.

<connectionStrings>
    <add 
        name="YourConnectionStringName" 
        connectionString="your-database-connection-string" 
        providerName="System.Data.SqlClient" />
</connectionStrings>

Customize as Needed

  • Log Levels: You can add more levels (e.g., Debug, Critical) as needed.
  • Additional Information: You can log any additional information that might be useful for troubleshooting.
  • Handling Logging Failures: Ensure that the logging mechanism itself doesn't cause your application to fail. You might want to implement fallback logging to a file or another medium in case the database is unavailable.

This approach provides a structured way to log and track errors in your application.

Next Recommended Reading Creating Dynamic Enums using C#