Manually render log template used in .NET logging

299 views Asked by At

In .NET one logs like so:

logger.LogInformation("Hello {What}", "World");

Which renders:

Hello World

I need to manually render that template (the upstream code is not mine and I can't redesign). I can't use string.Format(message, args) because that is not meant for structured logging.

Is there a method somewhere in Microsoft.Extensions.Logging (or elsewhere) which would allow me to do this? Something with the same signature as the logging methods:

string Render(string message, params object[] args);
1

There are 1 answers

0
lonix On BEST ANSWER

The Microsoft.Extensions.Logging namespace doesn't expose anything useful in this regard. So I had to write my own:

public string RenderLogMessage(string message, params object[] args)
{
  var pattern = @"(.*?{)(\w+?.+?)(}.*)";
  for (var i = 0; i < args.Length; i++)
  {
    message = Regex.Replace(message, pattern, $"$1 {i} $3", RegexOptions.None);
  }
  message = message.Replace("{ ", "{").Replace(" }", "}");

  return string.Format(message, args);
}

For my use case it assumes the template and args are correct (because they are also used in logger.LogX(message, args)). For a different use case, it would be wise to add error handling.