Get caller class

前端 未结 3 1166
小蘑菇
小蘑菇 2021-02-19 09:38

I\'m writing Logger and got problem with automatic adding class name, from which I called print_log method. For example something like this:

class Logger
  def s         


        
3条回答
  •  梦毁少年i
    2021-02-19 10:14

    I am not sure if it is possible to get the class name like you want. I would create a logger instance for this to which you can pass in the class name when creating it.

    class Logger
      def initialize(class_name)
        @class_name = class_name
      end
    
      def print_log(message)
        puts Time.now.strftime('%T | ') + @class_name + ' - ' + message
      end
    end
    
    class MyClass
      def initalize
        @logger = Logger.new self.class.name
        @logger.print_log 'called .new() method'
      end
    end
    

    More verbose than you would like maybe but explicit code that is easy to understand.

    For any serious work I recommend using the standard library logger. You may have to wrap it in your own call to get the log messages as you want it but you'll get log rotating and file handling as it should be.

提交回复
热议问题