Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby can one put the File and Line Number into the Logger.formatter?

Tags:

logging

ruby

I want an output format like:

/some/path/to/the/source/file(999) : the message to be logged

like image 456
peterk Avatar asked Jan 18 '26 18:01

peterk


1 Answers

This solution is dependent on the internal Logger call chain structure. So it would be nice for this to be suported by the Logger itself so it will be less brittle.

require 'logger'

...

module MyModule

@@_logger_ = Logger.new(STDOUT);

def self.log
    @@_logger_
end

def log
    @@_logger_
end

@@_logger_.formatter = proc do |severity, datetime, progname, msg|
    fileLine = "";
    caller.each do |clr|
        unless(/\/logger.rb:/ =~ clr)
            fileLine = clr;
            break;
        end
    end
    fileLine = fileLine.split(':in `',2)[0];
    fileLine.sub!(/:(\d)/, '(\1');
    "#{fileLine}) : #{msg}\n"
end
like image 87
peterk Avatar answered Jan 20 '26 15:01

peterk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!