Created
December 10, 2015 14:56
-
-
Save ifyouseewendy/dee74c73bbef87b38001 to your computer and use it in GitHub Desktop.
Log to different files based on logging level using Ruby logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'logger' | |
# Examples | |
# | |
# logger = DistinctFileLogger.new(STDOUT) | |
# logger.set_error_path('/Users/wendi/tmp/logger/error.log') | |
# logger.info "processing: 1/10" | |
# logger.info "processing: 2/10" | |
# logger.info "processing: 3/10" | |
# | |
# # STDOUT | |
# # I, [2015-12-10T22:30:06.749612 #63303] INFO -- : processing: 1/10 | |
# # I, [2015-12-10T22:30:06.749672 #63303] INFO -- : processing: 2/10 | |
# # I, [2015-12-10T22:30:06.749692 #63303] INFO -- : processing: 3/10 | |
# logger.error "Validation failed on :email" | |
# logger.error "Validation failed on :name" | |
# | |
# # error.log | |
# # # Logfile created on 2015-12-10 22:30:06 +0800 by logger.rb/47272 | |
# # E, [2015-12-10T22:30:06.749708 #63303] ERROR -- : Validation failed on :email | |
# # E, [2015-12-10T22:30:06.749729 #63303] ERROR -- : Validation failed on :name | |
class DistinctFileLogger | |
LOG_LEVEL = [:debug , :info , :warn , :error , :fatal , :unknown] | |
def initialize(path) | |
@loggers = {} | |
LOG_LEVEL.each do |level| | |
@loggers[level] = Logger.new(path) | |
end | |
end | |
LOG_LEVEL.each do |level| | |
define_method(level) do |message| | |
@loggers[level].send(level, message) | |
end | |
define_method("set_#{level}_path") do |path| | |
@loggers[level] = Logger.new(path) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment