Skip to content

Instantly share code, notes, and snippets.

@kryptykphysh
Last active October 10, 2016 16:45
Show Gist options
  • Save kryptykphysh/9419998 to your computer and use it in GitHub Desktop.
Save kryptykphysh/9419998 to your computer and use it in GitHub Desktop.
Ruby: Logging module with class names, output to both STDOUT and file
require 'logger'
module Logging
class MultiDelegator
def initialize(*targets)
@targets = targets
end
def self.delegate(*methods)
methods.each do |m|
define_method(m) do |*args|
@targets.map { |t| t.send(m, *args) }
end
end
self
end
class << self
alias to new
end
end
def logger
@logger ||= Logging.logger_for(self.class.name)
end
# Use a hash class-ivar to cache a unique Logger per class:
@loggers = {}
class << self
def logger_for(classname)
@loggers[classname] ||= configure_logger_for(classname)
end
def configure_logger_for(classname)
# Set up your log file
file = File.open(
'log/log_file.log',
File::WRONLY | File::APPEND | File::CREAT
)
# Force the buffer to flush on each write
file.sync = true
logger = Logger.new MultiDelegator.delegate(:write, :close).to(STDOUT, file)
logger.progname = classname
logger
end
end
end
# Then, in class files
class Thing
# Mix in the ability to log stuff ...
include Logging
# Much logging and output. Wow
def foo(bar)
logger.warn "About to foo the bar"
# commence foo-ing
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment