如何以一种漂亮、紧凑和通用的方式为所需的Ruby on Rails类正确创建专用记录器?



一切都在标题中,但为了它:

我工作的公司有一个非常大的Ruby On Rails应用程序。经过多年的开发,我们意识到它缺乏日志记录。生产事故有时真的很难追踪,因此也很难解决。

所以在我们的待办事项中有这个问题,需要改进整个日志系统。

当真正需要的时候,我开始在这里和那里为类添加自定义记录器,但是到处复制/粘贴那块逻辑似乎有点愚蠢。

所以我想知道:如何以一种漂亮,紧凑和通用的方式为所需的Ruby on Rails类正确创建专用日志记录器?

我的答案是使用ActiveSupport::Concern

这段代码很容易理解,并且有注释,所以我认为只要把它粘贴在这里就可以做出最好的解释:

# frozen_string_literal: true
# This concern can be included in any class to add a dedicated logger
# This will have the effect of creating a custom logger for the class
# The logger will be accessible through the `logger` class method and
# will create a log file in the `log` directory with the name of the class
# in snake case
# Example of use:
# class SampleClass
#   include DedicatedLoggerConcern
# end
#
# SampleClass.logger.info('Hello world')
#
# # Will write to log/sample_class.log
# :nocov:
module DedicatedLoggerConcern
extend ActiveSupport::Concern
included do
@logger = Logger.new(Rails.root.join('log', "#{name.underscore}.log"))
end
class_methods do
attr_reader :logger
end
end

代码注释说明了一切。这里没有什么突破性的,但我也认为这是正确使用ActiveSupport::Concern的一个很好的例子。我经常看到它被用作将太大的模型/控制器分割成不同逻辑块的方法(这可能也没有错),但我觉得这种将可能性添加到任何类的通用方法更像是要使用的(或者我错了吗?)。

请随意讨论,希望能有所帮助:)