Skip to content

Thread safe issue when ZLoggerConsoleOptions.LogToStandardErrorThreshold is used #188

@AlanLiu90

Description

@AlanLiu90

Description

Assuming a log entry is written by the second prcessor in DualAsyncLogProcessor. The processor calls IZLoggerEntry.Return, which set logInfo to default. Then the first processor checks if entry.LogInfo.LogLevel is less than LogToStandardErrorThreshold. Since logInfo has been set to default, its LogLevel is Trace, so the first processor will write it and call IZLoggerEntry.Return too.

Reproduction

using Microsoft.Extensions.Logging;
using ZLogger;

namespace ConsoleApp7
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using var loggerFactory = LoggerFactory.Create(logging =>
            {
                logging.SetMinimumLevel(LogLevel.Information);

                logging.AddZLoggerConsole(options =>
                {
                    options.InternalErrorLogger = ex => Console.WriteLine(ex);
                    options.LogToStandardErrorThreshold = LogLevel.Error;
                });
            });

            var logger = loggerFactory.CreateLogger("test");

            for (int i = 0; i < 10000; i++)
                logger.ZLogError($"{i}");
        }
    }
}

Envirionment:

  • .NET 8
  • Windows 10

Run the program and it will report many exceptions:

System.NullReferenceException: Object reference not set to an instance of an object.
   at ZLogger.ZLoggerEntry`1.ToString(IBufferWriter`1 writer) in D:\3rd\forks\ZLogger\src\ZLogger\ZLoggerEntry.cs:line 67
   at ZLogger.Formatters.PlainTextZLoggerFormatter.FormatLogEntry(IBufferWriter`1 writer, IZLoggerEntry entry) in D:\3rd\forks\ZLogger\src\ZLogger\Formatters\PlainTextZLoggerFormatter.cs:line 45
   at ZLogger.ZLoggerEntry`1.FormatUtf8(IBufferWriter`1 writer, IZLoggerFormatter formatter) in D:\3rd\forks\ZLogger\src\ZLogger\ZLoggerEntry.cs:line 76
   at ZLogger.AsyncStreamLineMessageWriter.WriteLoop() in D:\3rd\forks\ZLogger\src\ZLogger\AsyncStreamLineMessageWriter.cs:line 139

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions