Search code examples
c#serilog

How to deconstruct an array of string to pass it as params of Serilog in C#


I am working with Serilog.

I have this code

var message = "Age: {Age}, Weight: {Weight}";

// the list is ordered with the keys in the message
var elements = new List<string>{"15yo","60kgs"};

// call log method
logger.Log(LogLevel.Information, message, elements.ToArray());
// Expected log: 
"Age: 15yo, Weight: 60kgs"

// Actual log: 
"Age: ["15yo", "60kgs"], Weight: {Weight}"

Actually instead of deconstructing the array into multiple params, it takes the whole array as a single parameter and it replace the first key

Any help is needed.


Solution

  • You need to cast the input to object[] - this will call the correct overload of Log - the one with the [ParamArray], as opposed to the one that the IDE will show you if you hover (which is treating it as one arg, which just happens to be an array)

    elements.Cast<object>().ToArray()