Multi-threaded friendly logging for Console Mode C#?

Siegfried Heintze 1,861 Reputation points
2021-01-29T18:23:42.203+00:00

I have a Console Mode .NET Framework C# application for which I need to log some messages. Among the normal synchronous messages, I have calls to Task.Factory.StartNew to capture stdout and stderr from calling process.start and I would like to write the child process's stdout/stderr to a single log file shared with the parent.

What I have tried:

I have a crude home grown logging function that uses System.IO.File.AppendText and if it throws an exception (perhaps because the file is already open in another thread) I create a new unique log file name and write to that....

This is working but it is ugly.

I suppose I could try writing to a Microsoft Access database table -- would this accommodate multiple thread writing to the same table simultaneously? I'm hoping there is an easier solution!

What I would like:

Are there any logging packages that could help me? I have lots of log files resulting from multiple threads colliding while they try to write to the same log file and create a new unique log file name to write to. I would like a single log file that I could view with notepad.

Thanks

Siegfried

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,401 questions
{count} votes

1 additional answer

Sort by: Most helpful
  1. Alberto Poblacion 1,556 Reputation points
    2021-01-30T17:52:19.46+00:00

    How fast do you need it to be? If you do not mind a bit of contention between your threads, you can add a lock around the logging code and then you won't have any trouble appending the text to a single file:

    private object lockObject = new object();
    
    public Log(string text)
    {
        lock(lockObject)
        {
            using (StreamWriter sw = File.AppendText(path))
            {
                sw.WriteLine(text);
            }
        }
    }
    
    1 person found this answer helpful.
    0 comments No comments