Last active
April 1, 2016 19:37
-
-
Save jvmvik/0de1267052e2719bc59324abfbf1e919 to your computer and use it in GitHub Desktop.
Ruby logging wrapper. Allow: Add interceptor
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' | |
| module Log | |
| class << self | |
| def log | |
| @logger ||= Logger.new($stdout) | |
| @logger.formatter = proc do |severity, datetime, progname, msg| | |
| if(@interceptors) | |
| @interceptors.each { |interceptor| | |
| interceptor.call(severity, msg) | |
| } | |
| end | |
| "#{severity}> #{msg}\n" | |
| end | |
| @logger | |
| end | |
| def set_interceptors(it) | |
| @interceptors = it | |
| end | |
| def log=(logger) | |
| @logger = logger | |
| end | |
| end | |
| # Addition | |
| def self.included(base) | |
| class << base | |
| def logger | |
| Log.log.level = Logger::DEBUG if $debug == true | |
| Log.log | |
| end | |
| end | |
| end | |
| def log | |
| Log.log | |
| end | |
| # Register interceptor | |
| def interceptors(interceptors) | |
| return if interceptors.size == 0 | |
| raise 'Interceptors must be an array' unless interceptors.class == Array | |
| raise "Interceptor must be lambda expression" unless interceptors.first.class == Proc | |
| Log.set_interceptors(interceptors) | |
| end | |
| end |
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_relative 'lib/log' | |
| describe 'Log utility' do | |
| # Do not pass if included in a regression | |
| it 'Interceptor pattern' do | |
| class ILog | |
| include Log | |
| def initialize() | |
| log.warn('Hello world') # Not added to the stack | |
| end | |
| def log_hello_world | |
| log.warn('Hello world') # Add to the stack | |
| end | |
| end | |
| Log.log = Logger.new($stdout) | |
| # Keep track of the message | |
| stash = [] | |
| interceptor = lambda do |level, msg| | |
| stash << msg | |
| end | |
| # Create custom logger | |
| ilog = ILog.new() | |
| # Register interceptor | |
| ilog.interceptors([interceptor]) | |
| expect(stash.size).to eq(0) | |
| # Log something | |
| ilog.log_hello_world | |
| expect(stash.size).to eq(1) | |
| end | |
| end | |
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
| class Cat | |
| include Log | |
| def initialize() | |
| log.info('the cat is born') | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment