Skip to content

The combination of InMemory Logger and JsonFormatter does not seem to be thread-safe #206

Open
@s-shin

Description

@s-shin

Version: 2.5.10

Below is the reproduction code:

using Microsoft.Extensions.Logging;
using ZLogger;

using var factory = LoggerFactory.Create(logging =>
{
    logging.AddZLoggerInMemory(
        (options, provider) => { options.UseJsonFormatter(); },
        processor =>
        {
            processor.MessageReceived += s =>
            {
                // Console.WriteLine(s);
            };
        });
});
var logger = factory.CreateLogger<Program>();

var str = "";
for (var i = 0; i < 10; i++) str += $"test{i}";

var data = new Sample(str, 123456789, true);
var tasks = new List<Task>();
for (var i = 0; i < 2; i++)
{
    var task = Task.Run(() => { logger.ZLogInformation($"{data}"); });
    // and also
    // var task = Task.Run(() => { logger.LogInformation("{Data}", data); });
    tasks.Add(task);
}

await Task.WhenAll(tasks);

record Sample(string String, int Int, bool Bool);

The behavior is inconsistent (due to two parallel tasks, it occasionally works successfully). However, in most cases, exceptions occur related to JSON serialization, as shown below:

Unhandled exception. System.AggregateException: An error occurred while writing to logger(s). (Cannot advance past the end of the buffer, which has a size of 256.)
Unhandled exception. System.AggregateException: An error occurred while writing to logger(s). (The converter 'System.Text.Json.Serialization.Converters.BooleanConverter' wrote too much or not enough. Path: $.Bool.)

It seems that some kind of race condition occurs during the JSON serialization process.

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