Home > database >  Passing an MessageTemplate String to a Serilog Wrapper
Passing an MessageTemplate String to a Serilog Wrapper

Time:10-27

I have a question.

I have the following code (in C#):

public static void Warning(string log)
{
    Serilog.Log.Warning(log);
}

I would like to pass in a value that looks like such:

Serilog.Log.Warning("Checked out order {0} for ${1:C}", order.Id, order.Total);

Is there any way to pass the interpolated string (and its parameters) from a wrapper around Serilog so that I can get the benefit of having a MessageTemplate?

CodePudding user response:

Assuming you want to have a single wrapper around Log.Warning, then the method should have a message and a params:

public static void Warning(string msg, params object[] args)
{
    Serilog.Log.Warning(msg, args);
}

Usage would then be:

MyLogWrapper.Warning("Checked out order {0} for ${1:C}", order.Id, order.Total);

Consider using named parameters in the message to take full advantage of the fully structured logging:

MyLogWrapper.Warning("Checked out order {OrderId} for ${OrderTotal:C}", order.Id, order.Total);
  • Related