Latest changes in Rails 7
benchmark method to be called from anywhere.
Before this change, we could use it in views or controllers.
But, if we have to benchmark some methods in models or services we needed to do something like this:
This would log the details in the following way.
We could also use the following way to log the time taken by the specific method or a code.
The only problem is every time we need to benchmark we have to include the module in the class.
The above snippet will log the time taken by the operation:
After this change, we can use the benchmark method anywhere.
Now we don’t need to include any modules just for the purpose of benchmarking.
This will print the output in the logs depending on the log level (default log level is :info).
The benchmark method also accepts two options
We can set the log level to :debug, :info, :warn or :error to ensure the details only show up in specific environments.
The default log level value is :info.
This option will silence all log activity from within the block (except the benchmark timing information).
The above method will print the time taken by the expensive operation with log level :debug.
Any other logs inside the Rails.benchmark block won’t be shown in the server logs.
In our case, the first and last line inside the Rails.benchmark block won’t be printed.