1

Is ColoredConsoleAppender thread safe?

I have a multi-threaded console application where I use the log4net.Appender.ColoredConsoleAppender to get error messages printed in the console window.

I also use the non blocking console reader that is described here: https://stackoverflow.com/a/18342182/1688642

Occasionally the application blocks and pressing the Return-key (Enter) in the console removes the deadlock. This is always followed by an error from log4net (through the ColoredConsoleAppender). I suspect that there is a deadlock between the Console.ReadLine in the console reader and the writing inside the ColoredConsoleAppender (which is not a simple Console.WriteLine).

I have looked at the source code for ColoredConsoleAppender and it was a lot more involved than I thought and I suspect it is not thread safe.

I have also read about the potential deadlock that can happen between Console.ReadLine and Console.WriteLine described here: http://blogs.microsoft.co.il/dorony/2012/09/12/consolereadkey-net-45-changes-may-deadlock-your-system/ but I have concluded that this is not the same problem.

Update 1: The code below is an illustration, not the real code. And this code does not deadlock....

using System;
using System.IO;
using System.Reflection;
using System.Threading;
using log4net;
using log4net.Config;
...
class Program
{
    static void Main(string[] args)
    {
        var exeLocation = new FileInfo(Assembly.GetEntryAssembly().Location);
        var appConfig = new FileInfo(Path.Combine(exeLocation.DirectoryName, Assembly.GetEntryAssembly().GetName().Name + ".exe.config"));
        XmlConfigurator.Configure(appConfig);

        // Start two threads that writes log messages
        Thread t1 = new Thread(ThreadLoop);
        t1.Start("T1");

        Thread t2 = new Thread(ThreadLoop);
        t2.Start("T2");

        ILog log = LogManager.GetLogger("MAIN_LOG");
        Console.Write("$ ");
        while (true)
        {
            string line;
            if (Reader.TryReadLine(out line, 100))
            {
                bool handled = ParseAndExecuteCommand(line);
                if (!handled)
                {
                    Console.WriteLine("Unknown command (type 'h' to get help).");
                }
                Console.Write("$ ");
            }
            log.Info($"Info from main {Environment.TickCount}");
            Console.WriteLine($"Console.WriteLine from main {Environment.TickCount}");
        }
    }

    private static void ThreadLoop(object name)
    {
        while (true)
        {
            Thread.Sleep(1000);
            ILog log = LogManager.GetLogger("THREAD_LOG");
            log.Info($"Info from thread {name} {Environment.TickCount}");
            log.Warn($"Warning from thread {name}  {Environment.TickCount}");
            log.Error($"Error from thread  {name} {Environment.TickCount}");

            Console.WriteLine($"Console.WriteLine from thread {name} {Environment.TickCount}");
        }
    }

Below is the log4net configuration from App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>  
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="ERROR" />
        <foreColor value="Red, HighIntensity" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
      <threshold value="ERROR" />
    </appender>
    <root>
      <level value="INFO" />
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
</configuration>
Nils Lande
  • 860
  • 9
  • 14
  • You are logging to console in a console app? Is that right? Why not log to a file, then you can tail -f in a different console, without interference. Won't be colored, though. – Fildor Nov 21 '18 at 11:56
  • You should show a minimal, verifiable example. – Crowcoder Nov 21 '18 at 11:58
  • I log to text-files and UDP as well. From experience I know that people dont look at the logs very often. If they see a red text in the console window this tends to get their attention. – Nils Lande Nov 21 '18 at 13:46

1 Answers1

2

I have found the cause of my problem. It is not related to the ColoredConsoleAppender. Its a bug/feature of the Windows Command prompt that causes the problem.

If you enter selection mode in the Command Prompt all output is blocked (!). If Quick Edit mode is enabled it is sufficient to click inside the console window. The text marker will then change to a small filled rectangle indicating that the console is now in selection mode. Not easy to spot!

The issue is decribed here: Why is my command prompt freezing on Windows 10?

I have tested the ColoredConsoleAppender extensively using multiple theads and I have not found any deadlock. I have also read the source code for the appender.

The ColoredConsoleAppender is not thread safe, but the only real synchronisation problem I have found is that the text colors are mixed up. The color changes done by the appender may affect other threads that are writing to the console.

Source code for the appender can be found here:
https://github.com/apache/logging-log4net/blob/master/src/Appender/ColoredConsoleAppender.cs

UPDATE: The ManagedColoredConsoleAppender ( https://logging.apache.org/log4net/log4net-1.2.13/release/sdk/log4net.Appender.ManagedColoredConsoleAppender.html ) is a better alternative.

It will still block when the console enters selction mode, but it uses the standard Console.Out and Console.Error TextWriters. This makes it possible to write a non-blocking TextWriter which can be set with Console.SetOut() and Console.SetError(). The ManagedColoredConsoleAppender will use the new TextWriter while ColoredConsoleAppender will not.

Nils Lande
  • 860
  • 9
  • 14