跳至内容 跳至搜索

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
N
T

类公共方法

new(logger)

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

  if logger.formatter
    logger.formatter = logger.formatter.clone
  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 144
def flush
  clear_tags!
  super if defined?(super)
end

tagged(*tags)

# File activesupport/lib/active_support/tagged_logging.rb, line 133
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