为什么我们在 rails 记录器中使用块而不是字符串?

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

在Rails,

当我们使用 Logger class 时,我们总是在块中定义而不是 String -

Rails.logger.error { error.message }

不是以下方式-

Rails.logger.error "error.message"

背后的原因是什么?

查看此处的文档:

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).

因此您可以使用任一方法 - 传入 string 或传入 block。该块是一种优化,它将推迟插入字符串(以及示例中的任何属性信息),直到 Rails 知道它实际上会根据您的日志详细程度设置记录信息。