In Rails,
When we are using Logger class, we always define in blocks instead of String -
Rails.logger.error { error.message }
Not in following way -
Rails.logger.error "error.message"
What is the reason behind it ?
Take a look at the documentation here:
Impact of Logs on Performance
Another potential pitfall is that if you have many calls to Logger like this in your code:
logger.debug "Person attributes hash: #{@person.attributes.inspect}"
In the above example, There will be a performance impact even if the allowed output level doesn't include debug. The reason is that Ruby has to evaluate these strings, which includes instantiating the somewhat heavy String object and interpolating the variables, and which takes time. Therefore, it's recommended to pass blocks to the logger methods, as these are only evaluated if the output level is the same or included in the allowed level (i.e. lazy loading).
Therefore you can use either method - passing in a string
or passing in a block
. The block is an optimization that will defer interpolating the string (and any attribute information as in the example) until Rails knows it will actually be logging the info as per your log verbosity settings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With