Skip to content

ILogger mutates the array of objects to format #36165

@BrightSoul

Description

@BrightSoul

Hello there, I'm using ASP.NET Core 3.1. Basically the problem is the one described in the title. Here's how to reproduce.

Create a new ASP.NET Core application with dotnet new web
Change the Configure method of the Startup class like this.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/", async context =>
        {
            //Here's the relevant part of the repro
            var values = new object[] { null };
            logger.LogInformation("These are the values", values);

            //Is the first value still null?
            bool stillNull = values[0] == null;

            //It's not! This displays: "Still null: False, Value is: (null)"
            await context.Response.WriteAsync($"Still null: {stillNull}. Value is: {values[0]}");
        });
    });
}

As you can see, the original null value gets replaced with the string (null). It's a very subtle behavior by the ILogger service and I think this is not right. The original array should be left untouched.

Of course, the workaround is to make it log a copy of the array.

logger.LogInformation("These are the values", values.ToArray());

That yields: "Still null: True. Value is:"

I'm not sure if this is the intended behavior. The LogInformation method description doesn't say anything about mutating the provided array.

Thanks,
Moreno

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions