Skip to content

Commit

Permalink
Add ability to include handler options and change console styling
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Jul 13, 2019
1 parent 7663433 commit 1fc7eef
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
10 changes: 8 additions & 2 deletions lib/tty/logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,16 @@ def initialize(output: $stderr, level: nil, formatter: Formatters::Text,

# Add handler for logging messages
#
# @example
# add_handler(:console)
#
# @api public
def add_handler(handler)
name = coerce_handler(handler)
ready_handler = name.new(output: output, formatter: formatter, config: @config)
h, options = *(handler.is_a?(Array) ? handler : [handler, {}])
name = coerce_handler(h)
global_opts = {output: output, formatter: formatter, config: @config}
opts = global_opts.merge(options)
ready_handler = name.new(opts)
@ready_handlers << ready_handler
end

Expand Down
19 changes: 17 additions & 2 deletions lib/tty/logger/handlers/console.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,11 @@ class Console

attr_reader :config

def initialize(output: $stderr, formatter: nil, config: nil)
def initialize(output: $stderr, formatter: nil, config: nil, styles: {})
@output = output
@formatter = formatter
@config = config
@styles = styles
@mutex = Mutex.new
@pastel = Pastel.new
end
Expand All @@ -74,7 +75,7 @@ def initialize(output: $stderr, formatter: nil, config: nil)
def call(event)
@mutex.lock

style = STYLES[event.metadata[:name].to_sym]
style = configure_styles(event)
color = configure_color(style)

fmt = []
Expand All @@ -98,6 +99,20 @@ def call(event)
@mutex.unlock
end

# Merge default styles with custom style overrides
#
# @return [Hash[String]]
# the style matching log type
#
# @api private
def configure_styles(event)
style = STYLES[event.metadata[:name].to_sym].dup
(@styles[event.metadata[:name].to_sym] || {}).each do |k, v|
style[k] = v
end
style
end

def configure_color(style)
color = style.fetch(:color) { :cyan }
@pastel.send(color).detach
Expand Down
15 changes: 15 additions & 0 deletions spec/unit/handler_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@
"Logging \n"].join)
end

it "coerces name into handler object" do
config = TTY::Logger::Config.new
config.handlers = [
[:console, {styles: {info: {symbol: "+", label: "INFO"}}}]
]

logger = TTY::Logger.new(config: config, output: output)
logger.info("Logging")

expect(output.string).to eq([
"\e[32m+\e[0m ",
"\e[32mINFO\e[0m ",
"Logging \n"].join)
end

it "fails to coerce name into handler object" do
config = TTY::Logger::Config.new
config.handlers = [true]
Expand Down

0 comments on commit 1fc7eef

Please sign in to comment.