Capturing logger output inside a method

后端 未结 2 816
有刺的猬
有刺的猬 2021-02-10 14:57

New to Ruby I have a simple driver script right now that runs multiple test scripts in other ruby files. I have a method called RunScript() that runs the test scripts. The log

相关标签:
2条回答
  • I've done this in several different ways, and the most convenient I've found is to build a delegation object that routes messages to two or more loggers:

    require 'stringio'
    require 'logger'
    
    class LoggerTee
    
      def initialize *loggers
        @loggers = loggers
      end
    
      def method_missing meth, *args, &block
        @loggers.each { |logger| logger.send(meth, *args, &block) }
      end
    
    end
    
    capture_stringio = StringIO.new
    console_log = Logger.new(STDOUT)
    string_log = Logger.new(capture_stringio)
    log = LoggerTee.new(console_log, string_log)
    
    log.debug 'Hello world'
    puts capture_stringio.string
    

    Output:

    D, [2013-04-30T18:59:18.026285 #14533] DEBUG -- : Hello world
    D, [2013-04-30T18:59:18.026344 #14533] DEBUG -- : Hello world
    

    In this example, the LoggerTee class is instantiated with two separate loggers, one that goes to the console, the other to a StringIO instance. The resulting LoggerTee instance is a drop-in replacement for any standard logger object.

    0 讨论(0)
  • 2021-02-10 15:43

    Indeed there is no way to get the content of the logger without importing extra things. Here is a different solution. Because logger has only several logging methods you may simply make your own and log and collect logs in that function

       #the_logger - regular logger
       #the_arr - a global array to keep your logs in
       #the_string - log string
    
       def log_info(the_logger, the_arr, the_string)
    
           the_logger.info(the_string);
           the_arr.push(the_string);
       end
       .....................and use global the_arr to get your output
    

    Do this for 'debug', 'info', 'fatal' this is a simple way to use your log outputs as you run your program

    0 讨论(0)
提交回复
热议问题