In Rails,
When we are using Logger class, we always define in blocks instead of String -
当我们使用Logger类时,我们总是用块而不是String来定义 -
Rails.logger.error { error.message }
Not in following way -
不是以下方式 -
Rails.logger.error "error.message"
What is the reason behind it ?
它背后的原因是什么?
1 个解决方案
#1
Take a look at the documentation here:
看一下这里的文档:
日志对性能的影响
Another potential pitfall is that if you have many calls to Logger like this in your code:
另一个潜在的缺陷是,如果您在代码中有很多这样的Logger调用:
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).
在上面的示例中,即使允许的输出级别不包括调试,也会对性能产生影响。原因是Ruby必须评估这些字符串,包括实例化有点重的String对象并插入变量,这需要时间。因此,建议将块传递给记录器方法,因为只有在输出级别相同或包含在允许级别(即延迟加载)时才会对这些方法进行评估。
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.
因此,您可以使用任一方法 - 传入字符串或传入块。该块是一种优化,它将推迟插入字符串(以及示例中的任何属性信息),直到Rails知道它将根据您的日志详细程度设置实际记录信息。
#1
Take a look at the documentation here:
看一下这里的文档:
日志对性能的影响
Another potential pitfall is that if you have many calls to Logger like this in your code:
另一个潜在的缺陷是,如果您在代码中有很多这样的Logger调用:
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).
在上面的示例中,即使允许的输出级别不包括调试,也会对性能产生影响。原因是Ruby必须评估这些字符串,包括实例化有点重的String对象并插入变量,这需要时间。因此,建议将块传递给记录器方法,因为只有在输出级别相同或包含在允许级别(即延迟加载)时才会对这些方法进行评估。
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.
因此,您可以使用任一方法 - 传入字符串或传入块。该块是一种优化,它将推迟插入字符串(以及示例中的任何属性信息),直到Rails知道它将根据您的日志详细程度设置实际记录信息。