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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With