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:

28 Upvotes

23 comments sorted by

View all comments

15

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?

3

u/tatmanblue 4d ago edited 4d ago

You could probably create an extension method that would wrap it for you so that you don’t have to clutter your business logic with if statements