Class: Lennarb::Logger

Inherits:
Object
  • Object
show all
Defined in:
lib/lennarb/logger.rb

Constant Summary collapse

LEVELS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

{
  debug: ::Logger::DEBUG,
  info: ::Logger::INFO,
  warn: ::Logger::WARN,
  error: ::Logger::ERROR,
  fatal: ::Logger::FATAL
}.freeze
DEFAULT_FORMATTER =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

proc do |options|
  line = [options[:tag], options[:message]].compact.join(" ")
  "#{line}\n"
end

Instance Method Summary collapse

Constructor Details

#initialize(logger = ::Logger.new($stdout, level: ::Logger::INFO), formatter: DEFAULT_FORMATTER, tag: nil, tag_color: nil, message_color: nil, colorize: false) ⇒ Logger

Initialize a new logger

Parameters:

  • logger (::Logger) (defaults to: ::Logger.new($stdout, level: ::Logger::INFO))

    Logger instance to use

  • formatter (Proc) (defaults to: DEFAULT_FORMATTER)

    Custom formatter for messages

  • tag (Array, String, Symbol, nil) (defaults to: nil)

    Tag to identify log messages

  • tag_color (Symbol, nil) (defaults to: nil)

    Color for the tag

  • message_color (Symbol, nil) (defaults to: nil)

    Color for the message

  • colorize (Boolean) (defaults to: false)

    Force colorization even when not TTY



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/lennarb/logger.rb', line 26

def initialize(
  logger = ::Logger.new($stdout, level: ::Logger::INFO),
  formatter: DEFAULT_FORMATTER,
  tag: nil,
  tag_color: nil,
  message_color: nil,
  colorize: false
)
  @logger = logger.dup
  @logger.formatter = proc { |*args| format_log(*args) }
  @tag = Array(tag)
  @formatter = formatter
  @tag_color = tag_color
  @message_color = message_color
  @colorize = colorize || $stdout.tty?
end

Instance Method Details

#tagged(*tags) {|logger| ... } ⇒ Logger

Create a new logger with additional tags

Examples:

With block

logger.tagged(:api) { |l| l.info("message") }

Without block

api_logger = logger.tagged(:api)
api_logger.info("message")

Parameters:

  • tags (Array<Symbol, String>)

    Additional tags

Yields:

  • (logger)

    Block to execute with the new logger

Returns:

  • (Logger)

    New instance with added tags



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/lennarb/logger.rb', line 55

def tagged(*tags)
  new_logger = Logger.new(
    @logger,
    formatter: @formatter,
    tag: @tag.dup.concat(tags),
    tag_color: @tag_color,
    message_color: @message_color,
    colorize: @colorize
  )

  yield new_logger if block_given?

  new_logger
end