class U::Log::Logger
A very simple logger and log context
Constants
- NL
Public Class Methods
new(out, format, data)
click to toggle source
out
is the log destination. Has a << method that takes a string. format
is what transforms the data into a string using the dump method data
is context data for the logger. Responds to to_h
.
# File lib/u-log.rb, line 36 def initialize(out, format, data) @out = out @format = format @data = data.to_h end
Public Instance Methods
compat()
click to toggle source
Returns a ::Logger-compatible object.
Make sure to require 'u-log/compat' before invoking this method.
# File lib/u-log.rb, line 66 def compat; Compat.new(self) end
context(data = {})
click to toggle source
Creates a derivative context so that `context(a: 1).context(b: 2)` is equivalent to `contect(a: 1, b: 2)`
# File lib/u-log.rb, line 49 def context(data = {}) return self unless data.to_h.any? with_data @data.merge(data.to_h) end
Also aliased as: merge
log(*args)
click to toggle source
Outputs the given arguments merged with the context.
# File lib/u-log.rb, line 43 def log(*args) @out << with_data(args_to_hash args).to_s + NL end
to_h()
click to toggle source
# File lib/u-log.rb, line 60 def to_h; @data; end
to_s()
click to toggle source
# File lib/u-log.rb, line 56 def to_s @format.dump(evaluate_procs @data) end
Protected Instance Methods
args_to_hash(args)
click to toggle source
# File lib/u-log.rb, line 80 def args_to_hash(args) return {} if args.empty? data = @data.dup # Allow the first argument to be a message if !args.first.respond_to? :to_h data.merge!(msg: args.shift) end args.inject(data) do |h, obj| h.merge! obj.to_h end data end
evaluate_procs(obj)
click to toggle source
# File lib/u-log.rb, line 74 def evaluate_procs(obj) obj.each_with_object({}) do |(k,v), merged| merged[k] = v.respond_to?(:call) ? (v.call rescue $!) : v end end
with_data(data)
click to toggle source
# File lib/u-log.rb, line 70 def with_data(data) self.class.new @out, @format, data end