Skip to content

Instantly share code, notes, and snippets.

@brand-it
Last active March 5, 2024 19:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brand-it/59048fa1295a16cc99a07156cd8facd6 to your computer and use it in GitHub Desktop.
Save brand-it/59048fa1295a16cc99a07156cd8facd6 to your computer and use it in GitHub Desktop.
logger for scripting
# A nice way to add color to strings
class PrettyString < String
# https://no-color.org/
NO_COLOR = ENV.key?('NO_COLOR') || `tput colors`.chomp.to_i < 8
ANSI_COLORS = {
white: 0,
red: 31,
green: 32,
yellow: 33,
blue: 34,
magenta: 35
}.freeze
ANSI_COLORS.each do |name, code|
define_method(name) { NO_COLOR ? self : "\e[#{code}m#{self}\e[0m" }
end
end
# Standard logging to STDOUT
# Logger.info('foo')
# Logger.info('foo', 'bar')
# Logger.debug { ['foo', 'bar'] }
# Logger.obscure('something something')
# Logger.level = :debug
class Logger
LEVELS = %i[debug info warn error].freeze
class << self
def log_level=(level)
@log_level = LEVELS.index(level.to_sym)
end
def log_level
@log_level ||= LEVELS.index(:info)
end
def info(*messages)
log(messages, :white) if loggable?(:info)
end
def error(*messages)
log(messages, :red) if loggable?(:error)
end
def warn(*messages)
log(messages, :yellow) if loggable?(:warn)
end
def success(*messages)
log(messages, :green) if loggable?(:critical)
end
def debug(&block)
log(block.call, :magenta) if loggable?(:debug)
end
def loggable?(level)
LEVELS.index(level) >= log_level
end
def log(*messages, color)
Array(messages).flatten.each do |message|
puts PrettyString.new(message).public_send(color)
end
end
def obscure(string)
string = string.to_s
total_obscured = [string.length - 4, string.length].max
"#{'*' * total_obscured}#{string[-4, 4]}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment