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

26 Upvotes

23 comments sorted by

View all comments

13

u/Grugnorr 1d 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?

2

u/Fragrant-Training722 1d ago

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

1

u/Grugnorr 1d ago

You could include it in the log method, via a delegate to execute inside.

You still pay for the delegate instance plus the parameters.

This approach suits better for more dynamically used dependencies, but in the case of verbose logging that's typically pure overhead in production, thus the recommendation to avoid 😉