Leon's Blogging

Coding blogging for hackers.

Ruby - MultiIO Logger

| Comments

logger 可以方便我們去找尋問題在哪邊,因此設定好 logger 訊息是非常重要的

在 ruby 中,可以自定義 logger 的 level 還有 format,和輸出方式等等

1
2
3
4
5
6
7
8
9
10
#設定 logger 的輸出
logger = Logger.new(STDOUT)

#設定 logger level
logger.level = Logger::INFO

#設定 logger formatter
logger.formatter = proc do |severity, datetime, progname, msg|
  "#{msg}\n"
end
1
2
3
4
5
6
7
8
# Message in a block.
logger.fatal { "Argument 'foo' not given." }
# Message as a string.
logger.error "Argument #{@foo} mismatch."
# With progname.
logger.info('initialize') { "Initializing..." }
# With severity.
logger.add(Logger::FATAL) { 'Fatal error!' }

MultiIO

同時輸出到 terminal & file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Logger < ::Logger
  class << self
    def default(log)
      # 設定兩種要輸出的 io 方式
      io = [STDOUT, log_file]
      logger = Logger.new(MultiIO.new(*io))
      # 設定 log 層級
      logger.level = Logger::INFO
      # 設定每次輸出 log 的格式
      logger.formatter = proc do |_severity, _datetime, _progname, msg|
        "#{msg}\n"
      end
      logger
    end

    def log_file
      time = Time.now.strftime('%Y-%m-%dT%H:%M:%S')
      FileUtils.mkdir_p('./sample')
      log_file = File.open("./sample/#{time}.log", 'a')
      log_file
    end
  end
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MultiIO
  def initialize(*targets)
    @targets = targets
  end

  def write(args)
      # 每個 io 都寫入
    @targets.each { |target| target.write(args) }
  end

  def close
    # 寫入完要 close
    @targets.each(&:close)
  end
end

官方文件:

參考文件:

Comments