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

ogsagwnx  于 2023-04-05  发布在  Ruby
关注(0)|答案(1)|浏览(80)

一切都在标题中,但为了它:
我工作的公司有一个非常大的Ruby On Rails应用程序。经过多年的开发,我们意识到它缺乏日志记录。生产事件有时很难跟踪,因此很难解决。
所以我们的backlog中有一个改进整个日志记录系统的问题。
我开始在这里和那里为类添加自定义日志记录器,当真正需要的时候,但是到处复制/粘贴那块逻辑似乎有点愚蠢。
所以我想:如何为所需的Ruby on Rails类正确创建专用的日志记录器,以一种漂亮,紧凑和通用的方式?

e0bqpujr

e0bqpujr1#

我的答案是使用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的一个很好的例子。我经常看到它被用作将太大的模型/控制器拆分为不同逻辑块的方法。(这可能也没有错)但是我觉得这种泛型的方式来为任何类添加一个可能性更像是要被使用的(还是我错了?)。
大家可以自由讨论,希望这对大家有帮助:)

相关问题