Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting module of caller in Ruby
    primarykey
    data
    text
    <p>We have code to log data in our Ruby 1.8.6 web application. You call it roughly as follows:</p> <pre><code>$log.info("Some text here") </code></pre> <p>Now, in the logged output, I would like to include the module where that line appeared. I know that the <code>Kernel#caller</code> will give me an array where I can pull out the file and line number that the log line occurred, but I don't want that. I want the module, not the file name. The obvious solution is to modify the log line so that it reads like:</p> <pre><code>$log.info("Some text here", self.class.name) </code></pre> <p>and then parse the result. That's not going to work, though, because I am trying to extract this information in the default case. That is, I need the solution to work if the programmer forgot to specify the module, the second parameter to the log line.</p> <p>Is there any way to do this? If not, I will just have to make do with the <code>caller</code> array; most of our modules are in separate directories, so this would be an 80% solution.</p> <p>More complete example, please excuse minor syntax errors:</p> <p>in file log.rb:</p> <pre><code>module Log class Logger def info(msg, mod = '') puts "Module: #{mod} Msg: #{msg}" end end # class Logger end # module Log $log = Log::Logger.new </code></pre> <p>in file foo.rb:</p> <pre><code>module Foo class Bar def do_something # Do not pass in self.class.name. # We want the output to look like: # Module: Foo Msg: I did something! $log.info "I did something!" end end # class Bar end #module Foo </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload