Get caller class

前端 未结 3 1145
小蘑菇
小蘑菇 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条回答
  •  你的背包
    2021-02-19 10:15

    You can use module like that (Rails style):

    module Loggable
      extend ActiveSupport::Concern
    
      def log_prefix
        @log_prefix ||= (self.class == Class ? "#{self.to_s}" : "#{self.class.to_s}").freeze
      end
    
      included do
        [:debug, :info, :warn, :error, :fatal].each do |level|
          define_method level do |str = nil|
            caller = caller_locations(1,1)[0].label
            prefix = "[#{log_prefix}##{caller}] "
            prefix << level.to_s.upcase[0]
            str = "#{prefix}: #{str}"
            puts str if ENV["DEBUG"]
            Rails.logger.send(level, str)
          end
        end
      end
    end
    

    and you code will be:

    class MyClass
      include Loggable
      extend Loggable
    
      def instance_method
        debug "Hello"
      end
    
      def self.klass_method
        debug "Klass"
      end
    end
    

提交回复
热议问题