Capturing logger output inside a method

后端 未结 2 523
长发绾君心
长发绾君心 2021-02-10 15:01

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条回答
  •  孤独总比滥情好
    2021-02-10 15:41

    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.

提交回复
热议问题