나는 여러 가지 방법으로 이런 짓을했습니다, 그리고 내가 발견 한 가장 편리한이 위임 객체를 구축하는 것입니다 두 개 이상의 로거 경로 메시지 :
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
출력 :
D, [2013-04-30T18:59:18.026285 #14533] DEBUG -- : Hello world
D, [2013-04-30T18:59:18.026344 #14533] DEBUG -- : Hello world
이 예제에서 LoggerTee 클래스는 두 개의 개별 로거로 인스턴스화됩니다. 하나는 콘솔로 이동하고 다른 하나는 StringIO 인스턴스로 이동합니다. 결과적으로 생성 된 LoggerTee 인스턴스는 표준 로거 객체를 대체합니다.
약간의 수정을 거친 후 로그가 출력됩니다. – sng
같은 문제가있는 다른 사람들을 위해 나는 run 메소드 시작 부분에 @@ capture_stringio.truncate (@@ capturestringio.rewind)를 추가하여 다음 스크립트의 로그 내용을 지울 수 있도록했습니다. – sng