[CSHARP-4242] Do not use interpolated strings for logging Created: 05/Jul/22  Updated: 16/Aug/22  Resolved: 16/Aug/22

Status: Closed
Project: C# Driver
Component/s: Logging
Affects Version/s: None
Fix Version/s: 2.18.0

Type: Improvement Priority: Unknown
Reporter: James Kovacs Assignee: Boris Dogadov
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Epic Link: Integrate with .NET Logging API
Quarter: FY23Q2

 Description   

Interpolated strings are rendered immediately rather than captured. For example:

var greeting = "world";
var message = $"Hello, {greeting}!";
 
Log(() => message);
 
void Log(Func<string> func) {
    Console.WriteLine(func());
}

The intent is to only render the string in the Log method if it is needed. However looking at the decompiled MSIL, we can see that the rendered message is passed into the lambda, not the format string and arguments:

using System;
using System.Runtime.CompilerServices;
 
[CompilerGenerated]
internal class Program
{
	private static void <Main>$(string[] args)
	{
		<>c__DisplayClass0_0 CS$<>8__locals0 = new <>c__DisplayClass0_0();
		string greeting = "world";
		CS$<>8__locals0.message = "Hello, " + greeting + "!";
		Log(() => CS$<>8__locals0.message);
		[CompilerGenerated]
		static void Log(Func<string> func)
		{
			Console.WriteLine(func.Invoke());
		}
	}
}

We do this throughout our logging code. For example in DnsMonitor:

var message = $"Unhandled exception in DnsMonitor: {exception}.";
var sdamInformationEvent = new SdamInformationEvent(() => message);
_sdamInformationEventHandler(sdamInformationEvent);

We should change all usages of interpolated strings in logging to use the classic format string plus arguments approach to reduce the cost of logging when no listeners are configured.



 Comments   
Comment by Githook User [ 15/Aug/22 ]

Author:

{'name': 'BorisDog', 'email': 'BorisDog@users.noreply.github.com', 'username': 'BorisDog'}

Message: CSHARP-4242: Do not use interpolated strings for logging
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/3256d174aec4a0b6f47135d21683b7fdab67c051

Generated at Wed Feb 07 21:47:39 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.