Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we are using blocks instead of string in rails logger?

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 ?

like image 455
Amit Suroliya Avatar asked May 09 '15 19:05

Amit Suroliya


1 Answers

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.

like image 95
14 revs, 12 users 16% Avatar answered Oct 22 '22 10:10

14 revs, 12 users 16%