将线程ID添加到ruby日志中

时间:2014-06-16 09:34:27

标签: ruby multithreading logging

我正在以下列方式创建我的记录器:

Logging.color_scheme( 'bright',
    :levels => {
        :info  => :green,
        :warn  => :yellow,
        :error => :red,
        :fatal => [:white, :on_red]
    },
    :date => :blue,
    :logger => :cyan,
    :message => :magenta
)
@logger = Logging.logger['main_logger']
@logger.add_appenders(
    Logging.appenders.stdout,
    Logging.appenders.file('file',
       :filename => LOG_FILE_PATH,
       :layout => Logging.layouts.pattern(:pattern => '[%d] %-5l %c: %m\n')
    )
)

我想将线程id添加到每条日志消息(Thread.current.object_id),有没有办法可以做到?

1 个答案:

答案 0 :(得分:5)

您必须使用映射的诊断上下文'mdc'(请参阅https://github.com/TwP/logging/blob/master/examples/mdc.rb

以下是我的工作:

Logging.appenders.stdout(
      'stdout',
      :layout => Logging.layouts.pattern(
          :pattern => '%d %-5l [%X{tid}]: %m\n',
          :date_pattern => "%d/%m/%Y %H:%M:%S",
          :color_scheme => 'bright'
      ),
  )

并在你的帖子中,指出潮汐字段的值:

Logging.mdc['tid'] = Thread.current.object_id