Class: Tengine::Support::NamedLogger

Inherits:
Logger
  • Object
show all
Defined in:
lib/tengine/support/named_logger.rb

Constant Summary collapse

LOG_FORMAT =
"\e[%dm[%s #%5d %s %3d] %5s %s\n\e[0m".freeze
WHITE =
37

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, *args, &block) ⇒ NamedLogger

Returns a new instance of NamedLogger.



6
7
8
9
10
11
12
13
# File 'lib/tengine/support/named_logger.rb', line 6

def initialize(name, *args, &block)
  super(*args, &block)
  @name = name
  @mutex = Mutex.new
  @thread_nums ||= {}
  thread_num(Thread.main.object_id) # => 0 のはず
  self.formatter = method(:format_with_color)
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/tengine/support/named_logger.rb', line 5

def name
  @name
end

Instance Method Details

#format_with_color(severity, datetime, progname, message) ⇒ Object



28
29
30
31
32
33
# File 'lib/tengine/support/named_logger.rb', line 28

def format_with_color(severity, datetime, progname, message)
  tn = thread_num
  # http://d.hatena.ne.jp/keyesberry/20101107/p1
  color_no = (tn == 0) ? WHITE : WHITE - 1 - ((tn - 1) % 6) # メインスレッドを白、それ以外を色付きに
  LOG_FORMAT % [color_no, datetime.iso8601(6), Process.pid, @name, tn, severity, message]
end

#thread_num(tid = Thread.current.object_id) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/tengine/support/named_logger.rb', line 15

def thread_num(tid = Thread.current.object_id)
  result = @thread_nums[tid]
  return result if result
  @mutex.synchronize do
    num = @thread_nums[tid] = (@thread_nums.length)
    return num
  end
end