Nlog: Using string interpolation for structure log property names

Created on 27 Sep 2019  路  4Comments  路  Source: NLog/NLog

https://github.com/NLog/NLog/wiki/Performance

Don't use ... string interpolation (Ex $"Hello {world}") but pass the arguments to the log method.

Does this apply if using string interpolation for property names

```c#
const string CUSTOMER_NAME = "{CUSTOMER_NAME}"

myLogger.Info($"{CUSTOMER_NAME} placed an order",_cusName);
```

I want to use a constant so that property names would be consistent throughout a program.

performance question

All 4 comments

No sadly enough string interpolation was not created with logging-performance in mind. It is like calling string.Format upfront. But the DotNet-compiler can sometimes "optimize" the code, and make it into string.Concat. Not sure if it has a optimization path also for const-string. You have to ask Microsoft

Possible work around could be to make something similar to MEL LoggerMessage.Define Method

Creates a lamdba that is cached in a static-readonly-variable. This lambda takes parameters matching the number of args:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/loggermessage

https://github.com/NLog/NLog/wiki/Performance

Don't use ... string interpolation (Ex $"Hello {world}") but pass the arguments to the log method.

Does this apply if using string interpolation for property names

const string CUSTOMER_NAME = "{CUSTOMER_NAME}"

myLogger.Info($"{CUSTOMER_NAME} placed an order",_cusName);

I want to use a constant so that property names would be consistent throughout a program.

IMO this is a fine solution depending on your performance requirements. I depends also on the situation - e.g. is the log ignored (then the concat is wasted), does it log many times (then the concat is done every time)

How much the performance is different could be benchmarked.

PS I know some compilers will combine const strings as a compiler step, not sure if that's the case with the c# compiler. Edit related: https://github.com/dotnet/csharplang/issues/2077 and https://github.com/dotnet/csharplang/issues/384

thanks for the responses

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ErcinDedeoglu picture ErcinDedeoglu  路  3Comments

npandrei picture npandrei  路  3Comments

geedsen picture geedsen  路  3Comments

MaximRouiller picture MaximRouiller  路  3Comments

sszost picture sszost  路  3Comments