---
title: "How to to create async error log monitor in C# using file system?"  
description: "How to to create async error log monitor in C# using file system?"  
author: "ICSM Computer"  
published: 2025-05-29  
updated: 2025-05-29  
canonical: https://www.mindstick.com/interview/34179/how-to-to-create-async-error-log-monitor-in-c-sharp-using-file-system  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 3 minutes  

---

# How to to create async error log monitor in C# using file system?

```cs
public class GlobalExceptionHandler : ExceptionHandler
{
    public override async Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken = default)
    {
        var exception = context.Exception;
        var request = context.Request;

        int? errorLine = GetExceptionLineNumber(exception);
        string file = GetExceptionSourceFile(exception);

        var sb = new StringBuilder();

        sb.AppendLine($"Timestamp: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
        sb.AppendLine($"Message: {exception.Message}");
        sb.AppendLine("All Messages:");

        var ex = exception;
        while (ex != null)
        {
            sb.AppendLine($" - {ex.Message}");
            ex = ex.InnerException;
        }

        sb.AppendLine($"Stack Trace: {exception.StackTrace}");
        sb.AppendLine($"File: {file}");
        sb.AppendLine($"Error Line: {(errorLine.HasValue ? errorLine.ToString() : "N/A")}");

        if (request != null)
        {
            sb.AppendLine("Request Info:");
            sb.AppendLine($"  Method: {request.Method}");
            sb.AppendLine($"  URI: {request.RequestUri}");
            sb.AppendLine($"  Headers: {request.Headers}");
            if (request.Content != null)
            {
                string body = await request.Content.ReadAsStringAsync();
                sb.AppendLine($"  Body: {body}");
            }
        }

        sb.AppendLine(new string('-', 80));

        string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ErrorLogs", $"WebApiLog_{DateTime.Now:yyyyMMdd}.txt");
        Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));

        using (var stream = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, true))
        using (var writer = new StreamWriter(stream))
        {
            await writer.WriteLineAsync(sb.ToString());
        }

        // Optional: send a response
        context.Result = new ResponseMessageResult(
            context.Request.CreateResponse(HttpStatusCode.InternalServerError, new
            {
                error = "An unexpected error occurred."
            }));
    }

    // Extracts error line number from stack trace
    private int? GetExceptionLineNumber(Exception ex)
    {
        if (ex?.StackTrace == null)
            return null;

        var match = Regex.Match(ex.StackTrace, @":line (\d+)", RegexOptions.IgnoreCase);
        if (match.Success && int.TryParse(match.Groups[1].Value, out int line))
            return line;

        return null;
    }

    // Extracts source file path from stack trace
    private string GetExceptionSourceFile(Exception ex)
    {
        if (ex?.StackTrace == null)
            return null;

        var match = Regex.Match(ex.StackTrace, @"in (.*):line \d+", RegexOptions.IgnoreCase);
        if (match.Success)
            return match.Groups[1].Value.Trim();

        return null;
    }
}
```

## Answers

### Answer by ICSM Computer

```cs
public class GlobalExceptionHandler : ExceptionHandler
{
    public override async Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken = default)
    {
        var exception = context.Exception;
        var request = context.Request;

        int? errorLine = GetExceptionLineNumber(exception);
        string file = GetExceptionSourceFile(exception);

        var sb = new StringBuilder();

        sb.AppendLine($"Timestamp: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
        sb.AppendLine($"Message: {exception.Message}");
        sb.AppendLine("All Messages:");

        var ex = exception;
        while (ex != null)
        {
            sb.AppendLine($" - {ex.Message}");
            ex = ex.InnerException;
        }

        sb.AppendLine($"Stack Trace: {exception.StackTrace}");
        sb.AppendLine($"File: {file}");
        sb.AppendLine($"Error Line: {(errorLine.HasValue ? errorLine.ToString() : "N/A")}");

        if (request != null)
        {
            sb.AppendLine("Request Info:");
            sb.AppendLine($"  Method: {request.Method}");
            sb.AppendLine($"  URI: {request.RequestUri}");
            sb.AppendLine($"  Headers: {request.Headers}");
            if (request.Content != null)
            {
                string body = await request.Content.ReadAsStringAsync();
                sb.AppendLine($"  Body: {body}");
            }
        }

        sb.AppendLine(new string('-', 80));

        string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ErrorLogs", $"WebApiLog_{DateTime.Now:yyyyMMdd}.txt");
        Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));

        using (var stream = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, true))
        using (var writer = new StreamWriter(stream))
        {
            await writer.WriteLineAsync(sb.ToString());
        }

        // Optional: send a response
        context.Result = new ResponseMessageResult(
            context.Request.CreateResponse(HttpStatusCode.InternalServerError, new
            {
                error = "An unexpected error occurred."
            }));
    }

    // Extracts error line number from stack trace
    private int? GetExceptionLineNumber(Exception ex)
    {
        if (ex?.StackTrace == null)
            return null;

        var match = Regex.Match(ex.StackTrace, @":line (\d+)", RegexOptions.IgnoreCase);
        if (match.Success && int.TryParse(match.Groups[1].Value, out int line))
            return line;

        return null;
    }

    // Extracts source file path from stack trace
    private string GetExceptionSourceFile(Exception ex)
    {
        if (ex?.StackTrace == null)
            return null;

        var match = Regex.Match(ex.StackTrace, @"in (.*):line \d+", RegexOptions.IgnoreCase);
        if (match.Success)
            return match.Groups[1].Value.Trim();

        return null;
    }
}
```


---

Original Source: https://www.mindstick.com/interview/34179/how-to-to-create-async-error-log-monitor-in-c-sharp-using-file-system

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
