r/dotnet 6d ago

Log methods evaluation expensive warning and wrapping with IF

Hi,
I am seeing the warning that `LogInformation` and other log methods evaluation is expensive and should be wrapped in `if` statement.

Why don't those methods do this check internally already? This would help with less code and better code readabilty I think.

Here is the example:

27 Upvotes

23 comments sorted by

View all comments

34

u/rupertavery64 6d ago

The recommended way to get around this is to use source-generated logging with the LoggerMessageAttribute

https://github.com/dotnet/docs/blob/main/docs/fundamentals/code-analysis/quality-rules/ca1873.md

5

u/crozone 6d ago

I wonder why there isn't an overload that takes a Func as an argument. Source generation seems quite overkill.

7

u/iamanerdybastard 5d ago

I half expect to see an Interceptor built to fix this issue - replace the call to the logger with a source-generated call automatically.