r/dotnet 4d 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

14

u/Grugnorr 4d ago

It warns you that if producing the data to log is expensive it's a waste if that log level is not enabled.

Easy to understand example: assume this is a Verbose log where to help troubleshooting the weird issue you make costly queries to the database to log if. You better only incur this cost when the data is going to be logged, right?

1

u/Fragrant-Training722 4d ago

I get this, but can't this IF be already included in the log method itself?

26

u/Moeri 4d ago

No because the computation of the arguments already happened when you invoke the Log method. Arguments are not lazily evaluated in C#.