Beautiful

Something never changes, but something does.

增强ruby日志类

#ruby增强型日志封装。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Logger
  # Creates or opens a secondary log file.
  def attach(name)
    @logdev.attach(name)
  end

  # Closes a secondary log file.
  def detach(name)
    @logdev.detach(name)
  end

  class LogDevice # :nodoc:
    attr_reader :devs

    def attach(log)
      @devs ||= {}
      @devs[log] = open_logfile(log)
    end

    def detach(log)
      @devs ||= {}
      @devs[log].close
      @devs.delete(log)
    end

    alias_method :old_write, :write

    def write(message)
      old_write(message)
      #$ch << message
      @devs ||= {}
      @devs.each do |_, dev|
        dev.write(message)
      end
    end
  end
end
#使用示例:
$logger = Logger.new(STDOUT)
$logger_file = File.join(Dir.pwd, 'result.log')
$logger.attach($logger_file)
$logger.error 'logge error'
$logger.warn 'logge warn'
$logger.info 'logge info'