How to log custom object using ILogger in ASP.NET Core

2.4k views Asked by At

Some loggers are able to log custom object, e.g. in custom dimensions in application insights:

enter image description here

How do I add custom object to custom dimensions using ILogger?

I think I've previously used anonymous class for this:

Logger.LogInformation("Some Message {Parameter1} {Parameter2}", new 
{ 
    Parameter1 = "foo", //PropertyName must match message format
    Parameter2 = "foo", //PropertyName must match message format
    CustomData = customData
});

but the SimpleConsoleLogger is not working and causing an error:

System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

1

There are 1 answers

2
jgasiorowski On

I think your issue might be related with that Logger methods expects to get array of parameters params. You are passing object here.

Logger structured logs are not really matching your placeholders based on the name but actual order (in an array).

So instead on your usage you should really use and array as a parameter or pass your variables directly as params

Logger.LogInformation("Some Message {Parameter1} {Parameter2} {lastOne}", new object[]
{ 
    "foo",
    "foo",
    customData
});

// Or

Logger.LogInformation("Some Message {Parameter1} {Parameter2} {lastOne}", "foo", "foo", customData);

So the exception you are seeing is really saying that your string has 2 placeholders Parameter1 and Parameter2, but you provided just one object to LogInformation method, currently it cannot assign anything to your Parameter2.