Module: LogSwitch

Defined in:
lib/log_switch.rb,
lib/log_switch/mixin.rb,
lib/log_switch/version.rb

Overview

LogSwitch allows for extending a class/module with a logger and, most importantly, allows for turning off logging programmatically. See the README.rdoc for more info.

Defined Under Namespace

Modules: Mixin

Constant Summary collapse

VERSION =
'0.3.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#log(message, level = log_level) ⇒ Object

Logs a message using the level provided. If no level provided, use @log_level.

Parameters:

  • message (String)

    The message to log.

  • level (Symbol) (defaults to: log_level)

    The log level to send to your Logger.



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/log_switch.rb', line 65

def log(message, level=log_level)
  before.call unless before.nil?
  yield if block_given?

  if log?
    if message.respond_to? :each_line
      message.each_line { |line| logger.send level, line.chomp }
    else
      logger.send(level, message)
    end
  end
end

#log_levelSymbol

Returns The current default log level. Starts off as :debug.

Returns:

  • (Symbol)

    The current default log level. Starts off as :debug.



45
46
47
# File 'lib/log_switch.rb', line 45

def log_level
  @log_level ||= :debug
end

#loggerObject

Defaults to a Logger writing to STDOUT.



37
38
39
# File 'lib/log_switch.rb', line 37

def logger
  @logger ||= ::Logger.new STDOUT
end

Class Method Details

.extend_object(base) ⇒ Object

Saves the name of the class that extended itself with this module. Used by Mixin to know which class to include itself to.



12
13
14
15
# File 'lib/log_switch.rb', line 12

def self.extend_object(base)
  @extender = base
  super(base)
end

.extenderClass

Simply returns the name of the class that extended itself with this module. It’s set by extend_object.

Returns:

  • (Class)

    The class that extended itself with LogSwitch.



21
22
23
# File 'lib/log_switch.rb', line 21

def self.extender
  @extender
end

Instance Method Details

#before(&block) ⇒ Object

#log calls the block given to this method before it logs every time. This, thus, acts as a hook in the case where you want to make sure some code gets executed before you log a message. Useful for making sure a file exists before logging to it.

Parameters:

  • block (Proc)

    The block of code to execute before logging a message with #log.



56
57
58
# File 'lib/log_switch.rb', line 56

def before(&block)
  @before_block ||= block
end

#log?Boolean

Tells whether logging is turned on or not.

Returns:

  • (Boolean)


29
30
31
# File 'lib/log_switch.rb', line 29

def log?
  @log != false
end

#reset_config!Object

Sets back to defaults.



79
80
81
82
83
# File 'lib/log_switch.rb', line 79

def reset_config!
  self.log = true
  self.logger = ::Logger.new STDOUT
  self.log_level = :debug
end