color_scheme.rb
Created by Jeremy Hinegardner on 2007-01-24 Copyright 2007. All rights reserved
This is Free Software. See LICENSE and COPYING for details
This class defines a logging event.
CALLER_INDEX = 2
# File lib/logging.rb, line 139 139: def close 140: @appenders.each {|a| a.close} 141: h = ::Logging::Repository.instance.instance_variable_get :@h 142: h.delete(@name) 143: class << self; undef :close; end 144: end
Configures the Logging framework using the configuration information found in the given file. The file extension should be either ’.yaml’ or ’.yml’ (XML configuration is not yet supported).
# File lib/logging.rb, line 38 38: def configure( *args, &block ) 39: if block 40: return ::Logging::Config::Configurator.process(&block) 41: end 42: 43: filename = args.shift 44: raise ArgumentError, 'a filename was not given' if filename.nil? 45: 46: case File.extname(filename) 47: when '.yaml', '.yml' 48: ::Logging::Config::YamlConfigurator.load(filename, *args) 49: else raise ArgumentError, 'unknown configuration file format' end 50: end
This convenience method returns a Logger instance configured to behave similarly to a core Ruby Logger instance.
The device is the logging destination. This can be a filename (String) or an IO object (STDERR, STDOUT, an open File, etc.). The age is the number of old log files to keep or the frequency of rotation (daily, weekly, or monthly). The size is the maximum logfile size and is only used when age is a number.
Using the same device twice will result in the same Logger instance being returned. For example, if a Logger is created using STDOUT then the same Logger instance will be returned the next time STDOUT is used. A new Logger instance can be obtained by closing the previous logger instance.
log1 = Logging.logger(STDOUT) log2 = Logging.logger(STDOUT) log1.object_id == log2.object_id #=> true log1.close log2 = Logging.logger(STDOUT) log1.object_id == log2.object_id #=> false
The format of the log messages can be changed using a few optional parameters. The :pattern can be used to change the log message format. The :date_pattern can be used to change how timestamps are formatted.
log = Logging.logger(STDOUT, :pattern => "[%d] %-5l : %m\n", :date_pattern => "%Y-%m-%d %H:%M:%S.%s")
See the documentation for the Logging::Layouts::Pattern class for a full description of the :pattern and :date_pattern formatting strings.
# File lib/logging.rb, line 91 91: def logger( *args ) 92: return ::Logging::Logger if args.empty? 93: 94: opts = args.pop if args.last.instance_of?(Hash) 95: opts ||= Hash.new 96: 97: dev = args.shift 98: keep = age = args.shift 99: size = args.shift 100: 101: name = case dev 102: when String; dev 103: when File; dev.path 104: else dev.object_id.to_s end 105: 106: repo = ::Logging::Repository.instance 107: return repo[name] if repo.has_logger? name 108: 109: l_opts = { 110: :pattern => "%.1l, [%d #%p] %#{::Logging::MAX_LEVEL_LENGTH}l : %m\n", 111: :date_pattern => '%Y-%m-%dT%H:%M:%S.%s' 112: } 113: [:pattern, :date_pattern, :date_method].each do |o| 114: l_opts[o] = opts.delete(o) if opts.has_key? o 115: end 116: layout = ::Logging::Layouts::Pattern.new(l_opts) 117: 118: a_opts = Hash.new 119: a_opts[:size] = size if size.instance_of?(Fixnum) 120: a_opts[:age] = age if age.instance_of?(String) 121: a_opts[:keep] = keep if keep.instance_of?(Fixnum) 122: a_opts[:filename] = dev if dev.instance_of?(String) 123: a_opts[:layout] = layout 124: a_opts.merge! opts 125: 126: appender = 127: case dev 128: when String 129: ::Logging::Appenders::RollingFile.new(name, a_opts) 130: else 131: ::Logging::Appenders::IO.new(name, dev, a_opts) 132: end 133: 134: logger = ::Logging::Logger.new(name) 135: logger.add_appenders appender 136: logger.additive = false 137: 138: class << logger 139: def close 140: @appenders.each {|a| a.close} 141: h = ::Logging::Repository.instance.instance_variable_get :@h 142: h.delete(@name) 143: class << self; undef :close; end 144: end 145: end
Creates a new log event with the given logger name, numeric level, array of data from the user to be logged, and boolean trace flag. If the trace flag is set to true then Kernel::caller will be invoked to get the execution trace of the logging method.
# File lib/logging/log_event.rb, line 27 27: def initialize( logger, level, data, trace ) 28: f = l = m = '' 29: 30: if trace 31: stack = Kernel.caller[CALLER_INDEX] 32: return if stack.nil? 33: 34: match = CALLER_RGXP.match(stack) 35: f = match[1] 36: l = Integer(match[2]) 37: m = match[3] unless match[3].nil? 38: end 39: 40: super(logger, level, data, Time.now, f, l, m) 41: end
Access to the appenders.
# File lib/logging.rb, line 158 158: def appenders 159: ::Logging::Appenders 160: end
Without any arguments, returns the global exception backtrace logging value. When set to true backtraces will be written to the logs; when set to false backtraces will be suppressed.
When an argument is given the global exception backtrace setting will be changed. Value values are "on", :on<tt> and true to turn on backtraces and <tt>"off", :off and false to turn off backtraces.
# File lib/logging.rb, line 350 350: def backtrace( b = nil ) 351: @backtrace = true unless defined? @backtrace 352: return @backtrace if b.nil? 353: 354: @backtrace = case b 355: when :on, 'on', true; true 356: when :off, 'off', false; false 357: else 358: raise ArgumentError, "backtrace must be true or false" 359: end 360: end
Returns the color scheme identified by the given name. If there is no color scheme nil is returned.
If color scheme options are supplied then a new color scheme is created. Any existing color scheme with the given name will be replaced by the new color scheme.
# File lib/logging.rb, line 169 169: def color_scheme( name, opts = {} ) 170: if opts.empty? 171: ::Logging::ColorScheme[name] 172: else 173: ::Logging::ColorScheme.new(name, opts) 174: end 175: end
Consolidate all loggers under the given namespace. All child loggers in the namespace will use the “consolidated” namespace logger instead of creating a new logger for each class or module.
If the “root” logger name is passed to this method then all loggers will consolidate to the root logger. In other words, only the root logger will be created, and it will be used by all classes and modules in the application.
Logging.consolidate( 'Foo' ) foo = Logging.logger['Foo'] bar = Logging.logger['Foo::Bar'] baz = Logging.logger['Baz'] foo.object_id == bar.object_id #=> true foo.object_id == baz.object_id #=> false
# File lib/logging.rb, line 210 210: def consolidate( *args ) 211: ::Logging::Repository.instance.add_master(*args) 212: self 213: end
Defines the default obj_format method to use when converting objects into string representations for logging. obj_format can be one of :string, :inspect, or :yaml. These formatting commands map to the following object methods
:string => to_s
:inspect => inspect
:yaml => to_yaml
An ArgumentError is raised if anything other than :string, :inspect, :yaml is passed to this method.
# File lib/logging.rb, line 326 326: def format_as( f ) 327: f = f.intern if f.instance_of? String 328: 329: unless [:string, :inspect, :yaml].include? f 330: raise ArgumentError, "unknown object format '#{f}'" 331: end 332: 333: module_eval "OBJ_FORMAT = :#{f}", __FILE__, __LINE__ 334: self 335: end
Add a “logger” method to the including context. If included from Object or Kernel, the logger method will be available to all objects.
Optionally, a method name can be given and that will be used to provided access to the logger:
include Logging.globally( :log ) log.info "Just using a shorter method name"
If you prefer to use the shorter “log” to access the logger.
include Logging.globally class Foo logger.debug "Loading the Foo class" def initialize logger.info "Creating some new foo" end end logger.fatal "End of example"
# File lib/logging.rb, line 243 243: def globally( name = :logger ) 244: Module.new { 245: eval "def #{name}() @_logging_logger ||= ::Logging::Logger[self] end" 246: } 247: end
Defines the levels available to the loggers. The levels is an array of strings and symbols. Each element in the array is downcased and converted to a symbol; these symbols are used to create the logging methods in the loggers.
The first element in the array is the lowest logging level. Setting the logging level to this value will enable all log messages. The last element in the array is the highest logging level. Setting the logging level to this value will disable all log messages except this highest level.
This method should be invoked only once to configure the logging levels. It is automatically invoked with the default logging levels when the first logger is created.
The levels “all” and “off” are reserved and will be ignored if passed to this method.
Example:
Logging.init :debug, :info, :warn, :error, :fatal log = Logging::Logger['my logger'] log.level = :warn log.warn 'Danger! Danger! Will Robinson' log.info 'Just FYI' # => not logged
or
Logging.init %w(DEBUG INFO NOTICE WARNING ERR CRIT ALERT EMERG) log = Logging::Logger['syslog'] log.level = :notice log.warning 'This is your first warning' log.info 'Just FYI' # => not logged
# File lib/logging.rb, line 286 286: def init( *args ) 287: args = %(debug info warn error fatal) if args.empty? 288: 289: args.flatten! 290: levels = LEVELS.clear 291: names = LNAMES.clear 292: 293: id = 0 294: args.each do |lvl| 295: lvl = levelify lvl 296: unless levels.has_key?(lvl) or lvl == 'all' or lvl == 'off' 297: levels[lvl] = id 298: names[id] = lvl.upcase 299: id += 1 300: end 301: end 302: 303: longest = names.inject {|x,y| (x.length > y.length) ? x : y} 304: longest = 'off' if longest.length < 3 305: module_eval "MAX_LEVEL_LENGTH = #{longest.length}", __FILE__, __LINE__ 306: 307: initialize_plugins 308: levels.keys 309: end
Access to the layouts.
# File lib/logging.rb, line 152 152: def layouts 153: ::Logging::Layouts 154: end
Returns the library path for the module. If any arguments are given, they will be joined to the end of the library path using File.join.
# File lib/logging.rb, line 372 372: def libpath( *args, &block ) 373: rv = args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten) 374: if block 375: begin 376: $LOAD_PATH.unshift LIBPATH 377: rv = block.call 378: ensure 379: $LOAD_PATH.shift 380: end 381: end 382: return rv 383: end
Returns the lpath for the module. If any arguments are given, they will be joined to the end of the path using File.join.
# File lib/logging.rb, line 389 389: def path( *args, &block ) 390: rv = args.empty? ? PATH : ::File.join(PATH, args.flatten) 391: if block 392: begin 393: $LOAD_PATH.unshift PATH 394: rv = block.call 395: ensure 396: $LOAD_PATH.shift 397: end 398: end 399: return rv 400: end
Reopen all appenders. This method should be called immediately after a fork to ensure no conflict with file descriptors and calls to fcntl or flock.
# File lib/logging.rb, line 181 181: def reopen 182: log_internal {'re-opening all appenders'} 183: ::Logging::Appenders.each {|appender| appender.reopen} 184: self 185: end
This method is used to show the configuration of the logging framework. The information is written to the given io stream (defaulting to stdout). Normally the configuration is dumped starting with the root logger, but any logger name can be given.
Each line contains information for a single logger and it’s appenders. A child logger is indented two spaces from it’s parent logger. Each line contains the logger name, level, additivity, and trace settings. Here is a brief example:
root ........................... *info -T LoggerA ...................... info +A -T LoggerA::LoggerB ........... info +A -T LoggerA::LoggerC ........... *debug +A -T LoggerD ...................... *warn -A +T
The lines can be deciphered as follows:
1) name - the name of the logger 2) level - the logger level; if it is preceded by an asterisk then the level was explicitly set for that logger (as opposed to being inherited from the parent logger) 3) additivity - a "+A" shows the logger is additive, and log events will be passed up to the parent logger; "-A" shows that the logger will *not* pass log events up to the parent logger 4) trace - a "+T" shows that the logger will include trace information in generated log events (this includes filename and line number of the log message; "-T" shows that the logger does not include trace information in the log events)
If a logger has appenders then they are listed, one per line, immediately below the logger. Appender lines are pre-pended with a single dash:
root ........................... *info -T * <Appenders::Stdout:0x8b02a4 name="stdout"> LoggerA ...................... info +A -T LoggerA::LoggerB ........... info +A -T LoggerA::LoggerC ........... *debug +A -T LoggerD ...................... *warn -A +T * <Appenders::Stderr:0x8b04ca name="stderr">
We can see in this configuration dump that all the loggers will append to stdout via the Stdout appender configured in the root logger. All the loggers are additive, and so their generated log events will be passed up to the root logger.
The exception in this configuration is LoggerD. Its additivity is set to false. It uses its own appender to send messages to stderr.
# File lib/logging.rb, line 461 461: def show_configuration( io = STDOUT, logger = 'root', indent = 0 ) 462: logger = ::Logging::Logger[logger] unless ::Logging::Logger === logger 463: 464: logger._dump_configuration(io, indent) 465: 466: indent += 2 467: children = ::Logging::Repository.instance.children(logger.name) 468: children.sort {|a,b| a.name <=> b.name}.each do |child| 469: ::Logging.show_configuration(io, child, indent) 470: end 471: 472: self 473: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.