Skip to content

Instantly share code, notes, and snippets.

@timuruski
Created December 23, 2013 22:04
Show Gist options
  • Save timuruski/8105666 to your computer and use it in GitHub Desktop.
Save timuruski/8105666 to your computer and use it in GitHub Desktop.
require 'date'
module Blackboxx
class Logger
# TODO false value supresses logging
def initialize(output, options = {})
@output = output
@echo_to_stdout = options.fetch(:echo_to_stdout) { output != STDOUT }
end
def info(msg)
puts_to_output(msg, :info)
end
alias_method :puts, :info
def debug(msg)
STDOUT.puts(msg) if echo_to_stdout?
puts_to_output(msg, :debug)
end
def echo_to_stdout?; @echo_to_stdout end
protected
def puts_to_output(msg, level)
# Send unformatted output to STDOUT.
STDOUT.puts(msg) if echo_to_stdout?
msg = format(msg, level)
@output.puts(msg)
end
# Example format:
# INFO 2013-12-23 13:10:39 Importing mcwilliams/import/DigitalTastingNotes_20131223.csv
# DEBUG 2013-12-23 13:10:49 Importing mcwilliams/import/DigitalAwards_20131223.csv
def format(msg, level)
level = String(level).upcase
timestamp = Time.now.strftime('%Y-%m-%d %H:%M:%S')
"#{level} #{timestamp} #{msg}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment