3

I want an output format like:

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

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
peterk
  • 5,136
  • 6
  • 33
  • 47

2 Answers2

7

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
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
peterk
  • 5,136
  • 6
  • 33
  • 47
0

__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?

Community
  • 1
  • 1
Sachin Singh
  • 7,107
  • 6
  • 40
  • 80
  • 2
    Note the purpose of the above question/answer is not to know the file and line in the *current file* but to report the file and line of the place where log.debug(message) was called in the code whcich is not the file in which the method that formats and prints the log message for output is defined. – peterk Apr 07 '13 at 19:40
  • 1
    So are you hinting that maybe the is some "class" that is somehow passed in to an invocation of a method one can "eval" __LINE__ and __FILE__ in to get what I get above? like the arguments array or some other weirdness? – peterk Apr 07 '13 at 19:49