Rails logger debug block vs string argument

Rails debugger allows method call either with a block or a string argument. Passing string in a block gets evaluated only when it is needed. Both perform the same task of writing something to log file but there is a minor difference considering performance on memory allocation.

Passing string in a block gets evaluated only when it is needed. Whereas passing a string argument allocated memory for the string irrespective of its need.

Let’s take an example to understand this.

1. Passing string as an argument to logger

logger.debug "Something that is being logged here: #{params}"

The string argument "Something that is being logged here: #{params}" gets evaluated even though we might not need this. Rails logger does not print everything that is passed to it. Rails logger checks log level before something is logged.

Let’s say log level is set as info with

config.log_level = :info

and something is being logged with Logger#debug as given in example of above. Thus, Rails does not output as log level is not matched.

In this case, memory allocation for the string is unnecessary.

2. Passing block as an argument to logger

logger.debug { "Something that is being logged here: #{params}" }

It’s a simple change where we have wrapped the string to be printed in a block as shown above.

Considering the same situation above where,

  • Rails log level is set as info
  • Logger#debug is called with a block argument

Now, as the log level is not matched, debug method does not evaluate whatever that is passed in that block. This saves allocation of memory for the the string passed in block.

Conclusion

Considering large scale application, it is a good idea to always pass arguments to logger methods as a block argument. This can save up unnecessary memory unit allocations when we have extensive logging.