module TransitionalLogger
- Author
-
Elon Flegenheimer
- Copyright
-
Copyright © 2013 Elon Flegenheimer
- License
-
The MIT License (MIT)
A singleton logger accessible from ALL objects. It is intended to be used to:
-
send logger data to stdout OR
-
log to a file while consuming stdout & stderr data as log input OR
-
destroy stdout, stderr, & log data OR
-
do one of the above until transitioned to another of the above
The logger can be altered just like a normal Logger:
logger.level = Logger::WARN
Example usage:
TransitionalLogger.stdout logger.info 'this message goes through the logger to stdout' puts 'this works like usual' TransitionalLogger.file('/tmp/whatever.log') Object.new.logger.info 'this message goes through the logger to the file above' puts 'this message also goes through the logger above' TransitionalLogger.blackhole Object.new.logger.error 'this message disappears' puts 'this message disappears too!'
Constants
- VERSION
Public Class Methods
Creates a logger that consumes stdout, stderr, and all logger messages.
# File lib/transitional_logger.rb, line 59 def blackhole file('/dev/null') end
Creates the specified logger that is accessible from all objects. stdout and stderr are redirected to this logger.
Parameters match Logger#new.
# File lib/transitional_logger.rb, line 47 def file(*args) raise ArgumentError, 'Logger#new params must be specified for #file' if args.size == 0 reset if @streams @master_logger = infect_object(Logger.new(*args)) @streams = [$stdout, $stderr, $stdin] $stdout = CommandeeredOut.new(@master_logger) $stderr = CommandeeredErr.new(@master_logger) @master_logger end
Logger accessor - otherwise accessible from any object
# File lib/transitional_logger.rb, line 74 def logger @master_logger end
Reset the changes that this object has introduced
# File lib/transitional_logger.rb, line 64 def reset @master_logger = nil Object.send :remove_method, :logger rescue nil if @streams $stdout, $stderr = @streams[0..1] @streams = nil end end
Creates a logger that is accessible from all objects. The logger points to stdout. Stdout is otherwise unaffected.
# File lib/transitional_logger.rb, line 38 def stdout reset if @streams @master_logger = infect_object(Logger.new($stdout)) end
Private Class Methods
Define the logger method to return this in all objects
# File lib/transitional_logger.rb, line 81 def infect_object(logger) Object.send :define_method, :logger, ->{logger} logger end