Last active
August 29, 2015 14:05
-
-
Save nunommc/e33e7fc30a129ac335ea to your computer and use it in GitHub Desktop.
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' | |
require 'colorize' | |
# This class provides a way for other modules or classes to have a | |
# logger automatically available, not having to define any other methods | |
# | |
# Examples | |
# | |
# module Mod | |
# include Loggable.new(progname: 'bla') | |
# end | |
# | |
# class B | |
# include Mod | |
# end | |
# | |
# b = B.new | |
# b.logger.info 'Hello World' | |
# | |
# USEFUL LINKS: | |
# - http://solnic.eu/2012/08/13/subclassing-module-for-fun-and-profit.html | |
# | |
class Loggable < Module | |
def initialize(log_file: 'default', log_level: :info, progname: nil) | |
@log_file = log_file | |
@log_level= log_level.to_s | |
@progname = progname | |
end | |
def included(model) | |
super | |
define_accessors | |
end | |
private | |
def define_accessors | |
# define_method("log=") do |value| | |
# instance_variable_set(:@log, value) | |
# end | |
class_eval <<-RUBY | |
def logger | |
@logger ||= Logger.new("log/#{@log_file}.log").tap do |l| | |
l.level = Logger::const_get '#{@log_level.upcase}' | |
l.formatter = Logger::Formatter.new | |
l.progname = '#{@progname}' | |
l.info { "Starting logging for: #{@progname.blue.bold} @ #{@log_level.yellow}" } | |
end | |
end | |
RUBY | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment