gspoosi
gspoosi

Reputation: 365

Ruby Logger to add context information on each line

What happens:

$logger.info("progname"){"msg_line1\nmsg_line2"}
I, [2017-03-16T14:14:01.426134 #846807]  INFO -- progname: msg_line1
msg_line2

What I'd like to achieve:

$logger.info("progname"){"msg_line1\nmsg_line2"}
I, [2017-03-16T14:14:01.426134 #846807]  INFO -- progname: msg_line1
I, [2017-03-16T14:14:01.426134 #846807]  INFO -- progname: msg_line2

What I tried already:

$logger = Logger.new(STDOUT)
original_formatter = Logger::Formatter.new
$logger.formatter = proc { |severity, datetime, progname, msg|
   msg.each_line do |line|
     original_formatter.call(severity, datetime, progname, line)
   end
 }

What happend:

$logger.info("progname"){"msg_line1\nmsg_line2"}
msg_line1
msg_line2=> true

Can somebody help me out? I don't know why my code doesn't work.

Upvotes: 1

Views: 543

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54223

The formatter proc should return a string, not just delegate method calls to another formatter.

Right now, your proc returns the content of msg.each_line :

msg_line1
msg_line2

You could check that the formatter does the job correctly by adding p before original_formatter.call(.... It's just that you don't use the results.

Here's a modified version of your code :

require 'logger'

$logger = Logger.new(STDOUT)
original_formatter = Logger::Formatter.new
$logger.formatter = proc { |severity, datetime, progname, msg|
  msg.split("\n").map do |line|
    original_formatter.call(severity, datetime, progname, line)
  end.join
}

$logger.info('progname') { "msg_line1\nmsg_line2" }
# I, [2017-03-16T15:08:40.688193 #5372]  INFO -- progname: msg_line1
# I, [2017-03-16T15:08:40.688193 #5372]  INFO -- progname: msg_line2

Upvotes: 1

Related Questions