peterk
peterk

Reputation: 5444

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

I want an output format like:

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

Upvotes: 3

Views: 1506

Answers (2)

Sachin Singh
Sachin Singh

Reputation: 7225

__FILE__ and __LINE__ are sort of dynamic constants that hold the file and line that are currently executing.

What does class_eval <<-"end_eval", __FILE__, __LINE__ mean in Ruby?

Upvotes: 0

peterk
peterk

Reputation: 5444

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

Upvotes: 7

Related Questions