跳至内容 跳至搜索

Active Support 标记日志

包装任何标准的 Logger 对象以提供标记功能。

可以与代码块一起调用

logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
logger.tagged('BCX') { logger.info 'Stuff' }                                  # Logs "[BCX] Stuff"
logger.tagged('BCX', "Jason") { |tagged_logger| tagged_logger.info 'Stuff' }  # Logs "[BCX] [Jason] Stuff"
logger.tagged('BCX') { logger.tagged('Jason') { logger.info 'Stuff' } }       # Logs "[BCX] [Jason] Stuff"

如果在没有代码块的情况下调用,则将返回一个应用了标签的新日志记录器

logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
logger.tagged("BCX").info "Stuff"                 # Logs "[BCX] Stuff"
logger.tagged("BCX", "Jason").info "Stuff"        # Logs "[BCX] [Jason] Stuff"
logger.tagged("BCX").tagged("Jason").info "Stuff" # Logs "[BCX] [Jason] Stuff"

这由默认的 Rails.logger 使用,如 Railties 所配置,以便轻松地用子域、请求 ID 以及其他任何有助于调试多用户生产应用程序的内容标记日志行。

方法
F
L
N
T

类公共方法

logger(*args, **kwargs)

返回一个已使用标记日志记录关注点包装的 'ActiveSupport::Logger`。

# File activesupport/lib/active_support/tagged_logging.rb, line 117
def self.logger(*args, **kwargs)
  new ActiveSupport::Logger.new(*args, **kwargs)
end

new(logger)

# File activesupport/lib/active_support/tagged_logging.rb, line 121
def self.new(logger)
  logger = logger.clone

  if logger.formatter
    logger.formatter = logger.formatter.clone

    # Workaround for https://bugs.ruby-lang.org/issues/20250
    # Can be removed when Ruby 3.4 is the least supported version.
    logger.formatter.object_id if logger.formatter.is_a?(Proc)
  else
    # Ensure we set a default formatter so we aren't extending nil!
    logger.formatter = ActiveSupport::Logger::SimpleFormatter.new
  end

  logger.formatter.extend Formatter
  logger.extend(self)
end

实例公共方法

flush()

# File activesupport/lib/active_support/tagged_logging.rb, line 152
def flush
  clear_tags!
  super if defined?(super)
end

tagged(*tags)

# File activesupport/lib/active_support/tagged_logging.rb, line 141
def tagged(*tags)
  if block_given?
    formatter.tagged(*tags) { yield self }
  else
    logger = ActiveSupport::TaggedLogging.new(self)
    logger.formatter.extend LocalTagStorage
    logger.push_tags(*formatter.current_tags, *tags)
    logger
  end
end