Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add thread id to ruby logs

I am creating my logger in the following way:

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')
    )
)

I would like to add the thread id to each log message (Thread.current.object_id), is there a way i can do it ?

like image 611
gal Avatar asked Jun 16 '14 09:06

gal


1 Answers

You have to use the Mapped Diagnostic Context 'mdc' (see https://github.com/TwP/logging/blob/master/examples/mdc.rb)

Here is what I do :

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'
      ),
  )

and in your thread, indicate the value of tide field like that :

Logging.mdc['tid'] = Thread.current.object_id
like image 55
Thierry Avatar answered Oct 14 '22 10:10

Thierry