Class: Logger

Inherits:
Object show all
Defined in:
lib/utilrb/logger/io.rb,
lib/utilrb/logger/root.rb,
lib/utilrb/logger/indent.rb,
lib/utilrb/logger/log_pp.rb,
lib/utilrb/logger/silent.rb,
lib/utilrb/logger/forward.rb,
lib/utilrb/logger/hierarchy.rb

Defined Under Namespace

Modules: Forward, Hierarchy, HierarchyElement Classes: LoggerIO

Constant Summary collapse

LEVEL_TO_COLOR =
begin
    require 'pastel'
    colorizer = Pastel.new
    { 'DEBUG' => ->(t) { t },
      'INFO' =>  ->(t) { t },
      'WARN' =>  colorizer.magenta.detach,
      'ERROR' => colorizer.red.detach,
      'FATAL' => colorizer.red.bold.detach }
rescue LoadError
    Hash.new
end

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.pp_to_array(object) ⇒ Object


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/utilrb/logger/log_pp.rb', line 8

def self.pp_to_array(object)
    message =
        begin
            PP.pp(object, "")
        rescue Exception => formatting_error
            begin
              "error formatting object using pretty-printing\n" +
                  object.to_s +
              "\nplease report the formatting error: \n" + 
              formatting_error.full_message
            rescue Exception => formatting_error
              "\nerror formatting object using pretty-printing\n" +
                  formatting_error.full_message
            end
        end

    message.split("\n")
end

.Root(progname, base_level, &block) ⇒ Object

Defines a logger on a module, allowing to use that module as a root in a hierarchy (i.e. having submodules use the Logger::Hierarchy support)

If a block is given, it will be provided the message severity, time, program name and text and should return the formatted message.

This method creates a logger attribute in which the module can be accessed. Moreover, it includes Logger::Forward, which allows to access the logger's output methods on the module directly

Examples:

module MyModule
    extend Logger.Root('MyModule', Logger::WARN)
end

MyModule.info "text"
MyModule.warn "warntext"

Parameters:

  • progname (String)

    is used as the logger's program name

  • base_level (Integer/Symbol)

    is the level at which the logger is initialized, this can be either a symbol from [:DEBUG, :INFO, :WARN, :ERROR, :FATAL] or the integer constants from Logger::DEBUG, Logger::INFO, etc. This value is overriden if the BASE_LOG_LEVEL environment variable is set.


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/utilrb/logger/root.rb', line 42

def self.Root(progname, base_level, &block)
	begin	
        if ENV['BASE_LOG_LEVEL']
            env_level = ENV['BASE_LOG_LEVEL'].upcase.to_sym 
            # there is currently no disabled level on the ruby side
            # but fatal is the closest
            env_level = :FATAL if env_level == :DISABLE
            
            base_level = ::Logger.const_get( env_level ) 
        end
	rescue Exception
 raise ArgumentError, "Log level #{base_level} is not available in the ruby Logger"
	end

    console = @console
    formatter =
        if block then lambda(&block)
        elsif !LEVEL_TO_COLOR.empty?
            lambda do |severity, time, name, msg|
                LEVEL_TO_COLOR[severity].call("#{name}[#{severity}]: #{msg}\n")
            end
        else lambda { |severity, time, name, msg| "#{name}[#{severity}]: #{msg}\n" }
        end

    Module.new do
        include ::Logger::Forward
        include ::Logger::HierarchyElement

        def has_own_logger?; true end

        define_method :logger do
            if logger = super()
                return logger
            end

            logger = ::Logger.new(STDOUT)
            logger.level = base_level
            logger.progname = progname
            logger.formatter = formatter
            @__utilrb_hierarchy__default_logger = logger
        end
    end
end

Instance Method Details

#color(*args) ⇒ Object


28
29
30
31
# File 'lib/utilrb/logger/log_pp.rb', line 28

def color(*args)
    @color_generator ||= HighLine.new
    @color_generator.color(*args)
end

#format_message(severity, datetime, progname, msg) ⇒ Object

Overloaded from the base logger implementation to add the current indentation


67
68
69
70
71
72
73
# File 'lib/utilrb/logger/indent.rb', line 67

def format_message(severity, datetime, progname, msg)
    if !@nest_string
        @nest_string = " " * self.nest_size
    end
    msg = "#{@nest_string}#{msg}"
    (@formatter || @default_formatter).call(severity, datetime, progname, msg)
end

#io(level) ⇒ Object


21
22
23
# File 'lib/utilrb/logger/io.rb', line 21

def io(level)
    LoggerIO.new(self, level)
end

#log_pp(level, object, *first_line_format) ⇒ Object


34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/utilrb/logger/log_pp.rb', line 34

def log_pp(level, object, *first_line_format)
    send(level) do
        first_line = !first_line_format.empty? && defined?(HighLine)
        self.class.pp_to_array(object).each do |line|
            if first_line
                line = color(line, *first_line_format)
                first_line = false
            end
            send(level, line)
        end
        break
    end
end

#nest(size) ⇒ Object #nest(size) ⇒ Object #nest(size, log_level) ⇒ Object

Adds a certain number number of spaces to the current indentation level

Overloads:

  • #nest(size) ⇒ Object

    Permanently adds a number of spaces to the current indentation

    Parameters:

    • size (Integer)

      the number of spaces that should be added to nest_size

  • #nest(size) ⇒ Object

    Adds a number of spaces to the current indentation for the duration of the block, and restores the original indentation afterwards.

    Parameters:

    • size (Integer)

      the number of spaces that should be added to nest_size

  • #nest(size, log_level) ⇒ Object

    Shortcut for

    Examples:

    
    logger.send(log_level) do
      logger.nest(size) do
        ...
      end
    end

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/utilrb/logger/indent.rb', line 42

def nest(size, log_level = nil)
    if log_level
        send(log_level) do
            nest(size) do
                yield
            end
            return
        end
    end

    if block_given?
        begin
            current = self.nest_size
            self.nest_size += size
            yield
        ensure
            self.nest_size = current
        end
    else
        self.nest_size += size
    end
end

#nest_size=(new_value) ⇒ Object

Sets the absolute number of spaces that should be prepended to every message

You usually want to increment / decrement this with #nest


10
11
12
13
14
15
16
# File 'lib/utilrb/logger/indent.rb', line 10

def nest_size=(new_value)
    @nest_string = nil
    if new_value < 0
        raise ArgumentError, "negative value for nest_size. You probably have unbalanced nest calls"
    end
    @nest_size = new_value
end

#silentObject

Silences this logger for the duration of the block


3
4
5
6
7
8
# File 'lib/utilrb/logger/silent.rb', line 3

def silent
    current_level, self.level = self.level, Logger::FATAL + 1
    yield
ensure
    self.level = current_level
end