Class: Console::Log4rLogger::ColorConsoleOutputter

Inherits:
Log4r::StdoutOutputter
  • Object
show all
Defined in:
lib/color_console/log4r_logger.rb

Overview

Extends the Log4r StdoutOutputter, adding colorised logging output to the console.

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ ColorConsoleOutputter

Returns a new instance of ColorConsoleOutputter.



16
17
18
19
# File 'lib/color_console/log4r_logger.rb', line 16

def initialize(name, options = {})
    super(name, options)
    @console_width = Console.width || -1
end

Instance Method Details

#format(event) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/color_console/log4r_logger.rb', line 22

def format(event)
    @fg = case event.level
    when Log4r::INFO then :white
    when Log4r::CONFIG then :cyan
    when Log4r::WARNING then :yellow
    when Log4r::ERROR then :red
    when Log4r::DEBUG then :dark_gray
    else :light_gray
    end

    if event.data
        begin
            thread = Log4r::NDC.peek.to_s.upcase[0, 2]
            level = Log4r::LNAMES[event.level]
            case
            when event.data.is_a?(Exception) || (RUBY_ENGINE == 'jruby' &&
                                                 event.data.java_kind_of?(java.lang.Throwable))
                e = event.data
                msg = "%-8s %-2s  %s: %s\n" % [level, thread, e.class, e.message]
                bt = e.backtrace.take(3).map{ |s| "                 from #{s}" }.join("\n")
                msg += bt
            when event.data.is_a?(Array)
                msg = event.data
                case msg.first
                when String then msg[0] = "%-8s %-2s  %s" % [level, thread, msg[0]]
                when Array then msg[0][0] = "%-8s %-2s  %s" % [level, thread, msg[0][0]]
                end
            else
                msg_lines = Console.wrap_text(event.data, @console_width - 13)
                msg = ""
                msg_lines.each_with_index do |line, i|
                    fmt = "%-8s %-2s  %s" % [[level][i], [thread][i], line]
                    msg += fmt
                    msg += "\n" if @console_width < 0 || fmt.length < @console_width
                end
            end
            msg.chomp
        rescue Object => ex
            "(Unable to format event.data due to #{ex})\n"
        end
    end
end

#write(data) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/color_console/log4r_logger.rb', line 66

def write(data)
    if data.is_a?(Array)
        if data[0].is_a?(String) && (data.length == 0 || data[1].is_a?(Symbol))
            Console.puts(*data)
        else
            data.each do |chunk|
                Console.write(*chunk)
            end
            Console.puts
        end
    elsif data
        Console.puts(data, @fg)
    end
end