pjstadig-logging 1.1.4.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (70) hide show
  1. data/History.txt +219 -0
  2. data/README.rdoc +115 -0
  3. data/Rakefile +43 -0
  4. data/data/bad_logging_1.rb +13 -0
  5. data/data/bad_logging_2.rb +21 -0
  6. data/data/logging.rb +42 -0
  7. data/data/logging.yaml +63 -0
  8. data/data/simple_logging.rb +13 -0
  9. data/examples/appenders.rb +47 -0
  10. data/examples/classes.rb +41 -0
  11. data/examples/consolidation.rb +83 -0
  12. data/examples/formatting.rb +51 -0
  13. data/examples/hierarchies.rb +73 -0
  14. data/examples/layouts.rb +48 -0
  15. data/examples/loggers.rb +29 -0
  16. data/examples/names.rb +43 -0
  17. data/examples/simple.rb +17 -0
  18. data/lib/logging.rb +479 -0
  19. data/lib/logging/appender.rb +251 -0
  20. data/lib/logging/appenders.rb +120 -0
  21. data/lib/logging/appenders/buffering.rb +168 -0
  22. data/lib/logging/appenders/console.rb +60 -0
  23. data/lib/logging/appenders/email.rb +75 -0
  24. data/lib/logging/appenders/file.rb +58 -0
  25. data/lib/logging/appenders/growl.rb +197 -0
  26. data/lib/logging/appenders/io.rb +69 -0
  27. data/lib/logging/appenders/rolling_file.rb +293 -0
  28. data/lib/logging/appenders/string_io.rb +68 -0
  29. data/lib/logging/appenders/syslog.rb +194 -0
  30. data/lib/logging/config/configurator.rb +188 -0
  31. data/lib/logging/config/yaml_configurator.rb +191 -0
  32. data/lib/logging/layout.rb +117 -0
  33. data/lib/logging/layouts.rb +47 -0
  34. data/lib/logging/layouts/basic.rb +32 -0
  35. data/lib/logging/layouts/parseable.rb +211 -0
  36. data/lib/logging/layouts/pattern.rb +312 -0
  37. data/lib/logging/log_event.rb +51 -0
  38. data/lib/logging/logger.rb +503 -0
  39. data/lib/logging/repository.rb +210 -0
  40. data/lib/logging/root_logger.rb +61 -0
  41. data/lib/logging/stats.rb +278 -0
  42. data/lib/logging/utils.rb +207 -0
  43. data/lib/spec/logging_helper.rb +34 -0
  44. data/test/appenders/test_buffered_io.rb +176 -0
  45. data/test/appenders/test_console.rb +66 -0
  46. data/test/appenders/test_email.rb +170 -0
  47. data/test/appenders/test_file.rb +95 -0
  48. data/test/appenders/test_growl.rb +127 -0
  49. data/test/appenders/test_io.rb +129 -0
  50. data/test/appenders/test_rolling_file.rb +200 -0
  51. data/test/appenders/test_syslog.rb +194 -0
  52. data/test/benchmark.rb +86 -0
  53. data/test/config/test_configurator.rb +70 -0
  54. data/test/config/test_yaml_configurator.rb +40 -0
  55. data/test/layouts/test_basic.rb +42 -0
  56. data/test/layouts/test_json.rb +112 -0
  57. data/test/layouts/test_pattern.rb +198 -0
  58. data/test/layouts/test_yaml.rb +121 -0
  59. data/test/setup.rb +73 -0
  60. data/test/test_appender.rb +152 -0
  61. data/test/test_consolidate.rb +46 -0
  62. data/test/test_layout.rb +110 -0
  63. data/test/test_log_event.rb +80 -0
  64. data/test/test_logger.rb +699 -0
  65. data/test/test_logging.rb +267 -0
  66. data/test/test_repository.rb +158 -0
  67. data/test/test_root_logger.rb +81 -0
  68. data/test/test_stats.rb +274 -0
  69. data/test/test_utils.rb +116 -0
  70. metadata +175 -0
data/examples/names.rb ADDED
@@ -0,0 +1,43 @@
1
+ # :stopdoc:
2
+ #
3
+ # Loggers and appenders can be looked up by name. The bracket notation is
4
+ # used to find these objects:
5
+ #
6
+ # Logging.logger['foo']
7
+ # Logging.appenders['bar']
8
+ #
9
+ # A logger will be created if a new name is used. Appenders are different;
10
+ # nil is returned when an unknown appender name is used. The reason for this
11
+ # is that appenders come in many different flavors (so it is unclear which
12
+ # type should be created), but there is only one type of logger.
13
+ #
14
+ # So it is useful to be able to create an appender and then reference it by
15
+ # name to add it to multiple loggers. When the same name is used, the same
16
+ # object will be returned by the bracket methods.
17
+ #
18
+ # Layouts do not have names. Some are stateful, and none are threadsafe. So
19
+ # each appender is configured with it's own layout.
20
+ #
21
+
22
+ require 'logging'
23
+
24
+ Logging.appenders.file('Debug File', :filename => 'debug.log')
25
+ Logging.appenders.growl('Growl Notifier', :level => :error)
26
+
27
+ # configure the root logger
28
+ Logging.logger.root.appenders = 'Debug File'
29
+ Logging.logger.root.level = :debug
30
+
31
+ # add the growl notifier to the Critical logger (it will use it's own
32
+ # appender and the root logger's appender, too)
33
+ Logging.logger['Critical'].appenders = 'Growl Notifier'
34
+
35
+ # if you'll notice above, assigning appenders using just the name is valid
36
+ # the logger is smart enough to figure out it was given a string and then
37
+ # go lookup the appender by name
38
+
39
+ # and now log some messages
40
+ Logging.logger['Critical'].info 'just keeping you informed'
41
+ Logging.logger['Critical'].fatal 'WTF!!'
42
+
43
+ # :startdoc:
@@ -0,0 +1,17 @@
1
+ # :stopdoc:
2
+ #
3
+ # Logging provides a simple, default logger configured in the same manner as
4
+ # the default Ruby Logger class -- i.e. the output of the two will be the
5
+ # same. All log messags at "warn" or higher are printed to STDOUT; any
6
+ # message below the "warn" level are discarded.
7
+ #
8
+
9
+ require 'logging'
10
+
11
+ log = Logging.logger(STDOUT)
12
+ log.level = :warn
13
+
14
+ log.debug "this debug message will not be output by the logger"
15
+ log.warn "this is your last warning"
16
+
17
+ # :startdoc:
data/lib/logging.rb ADDED
@@ -0,0 +1,479 @@
1
+ require File.expand_path(
2
+ File.join(File.dirname(__FILE__), %w[logging utils]))
3
+
4
+ require 'yaml'
5
+ require 'stringio'
6
+ require 'thread'
7
+
8
+ HAVE_LOCKFILE = require? 'lockfile'
9
+ HAVE_SYSLOG = require? 'syslog'
10
+ require? 'fastthread'
11
+
12
+
13
+ # TODO: Windows Log Service appender
14
+
15
+ #
16
+ #
17
+ module Logging
18
+ # :stopdoc:
19
+ VERSION = '1.1.4'
20
+ LIBPATH = ::File.expand_path(::File.dirname(__FILE__)) + ::File::SEPARATOR
21
+ PATH = ::File.dirname(LIBPATH) + ::File::SEPARATOR
22
+ LEVELS = {}
23
+ LNAMES = []
24
+ # :startdoc:
25
+
26
+ class << self
27
+
28
+ # call-seq:
29
+ # Logging.configure( filename )
30
+ # Logging.configure { block }
31
+ #
32
+ # Configures the Logging framework using the configuration information
33
+ # found in the given file. The file extension should be either '.yaml'
34
+ # or '.yml' (XML configuration is not yet supported).
35
+ #
36
+ def configure( *args, &block )
37
+ if block
38
+ return ::Logging::Config::Configurator.process(&block)
39
+ end
40
+
41
+ filename = args.shift
42
+ raise ArgumentError, 'a filename was not given' if filename.nil?
43
+
44
+ case File.extname(filename)
45
+ when '.yaml', '.yml'
46
+ ::Logging::Config::YamlConfigurator.load(filename, *args)
47
+ else raise ArgumentError, 'unknown configuration file format' end
48
+ end
49
+
50
+ # call-seq:
51
+ # Logging.logger( device, age = 7, size = 1048576 )
52
+ # Logging.logger( device, age = 'weekly' )
53
+ #
54
+ # This convenience method returns a Logger instance configured to behave
55
+ # similarly to a core Ruby Logger instance.
56
+ #
57
+ # The _device_ is the logging destination. This can be a filename
58
+ # (String) or an IO object (STDERR, STDOUT, an open File, etc.). The
59
+ # _age_ is the number of old log files to keep or the frequency of
60
+ # rotation (+daily+, +weekly+, or +monthly+). The _size_ is the maximum
61
+ # logfile size and is only used when _age_ is a number.
62
+ #
63
+ # Using the same _device_ twice will result in the same Logger instance
64
+ # being returned. For example, if a Logger is created using STDOUT then
65
+ # the same Logger instance will be returned the next time STDOUT is
66
+ # used. A new Logger instance can be obtained by closing the previous
67
+ # logger instance.
68
+ #
69
+ # log1 = Logging.logger(STDOUT)
70
+ # log2 = Logging.logger(STDOUT)
71
+ # log1.object_id == log2.object_id #=> true
72
+ #
73
+ # log1.close
74
+ # log2 = Logging.logger(STDOUT)
75
+ # log1.object_id == log2.object_id #=> false
76
+ #
77
+ # The format of the log messages can be changed using a few optional
78
+ # parameters. The <tt>:pattern</tt> can be used to change the log
79
+ # message format. The <tt>:date_pattern</tt> can be used to change how
80
+ # timestamps are formatted.
81
+ #
82
+ # log = Logging.logger(STDOUT,
83
+ # :pattern => "[%d] %-5l : %m\n",
84
+ # :date_pattern => "%Y-%m-%d %H:%M:%S.%s")
85
+ #
86
+ # See the documentation for the Logging::Layouts::Pattern class for a
87
+ # full description of the :pattern and :date_pattern formatting strings.
88
+ #
89
+ def logger( *args )
90
+ return ::Logging::Logger if args.empty?
91
+
92
+ opts = args.pop if args.last.instance_of?(Hash)
93
+ opts ||= Hash.new
94
+
95
+ dev = args.shift
96
+ keep = age = args.shift
97
+ size = args.shift
98
+
99
+ name = case dev
100
+ when String; dev
101
+ when File; dev.path
102
+ else dev.object_id.to_s end
103
+
104
+ repo = ::Logging::Repository.instance
105
+ return repo[name] if repo.has_logger? name
106
+
107
+ l_opts = {
108
+ :pattern => "%.1l, [%d #%p] %#{::Logging::MAX_LEVEL_LENGTH}l : %m\n",
109
+ :date_pattern => '%Y-%m-%dT%H:%M:%S.%s'
110
+ }
111
+ [:pattern, :date_pattern, :date_method].each do |o|
112
+ l_opts[o] = opts.delete(o) if opts.has_key? o
113
+ end
114
+ layout = ::Logging::Layouts::Pattern.new(l_opts)
115
+
116
+ a_opts = Hash.new
117
+ a_opts[:size] = size if size.instance_of?(Fixnum)
118
+ a_opts[:age] = age if age.instance_of?(String)
119
+ a_opts[:keep] = keep if keep.instance_of?(Fixnum)
120
+ a_opts[:filename] = dev if dev.instance_of?(String)
121
+ a_opts[:layout] = layout
122
+ a_opts.merge! opts
123
+
124
+ appender =
125
+ case dev
126
+ when String
127
+ ::Logging::Appenders::RollingFile.new(name, a_opts)
128
+ else
129
+ ::Logging::Appenders::IO.new(name, dev, a_opts)
130
+ end
131
+
132
+ logger = ::Logging::Logger.new(name)
133
+ logger.add_appenders appender
134
+ logger.additive = false
135
+
136
+ class << logger
137
+ def close
138
+ @appenders.each {|a| a.close}
139
+ h = ::Logging::Repository.instance.instance_variable_get :@h
140
+ h.delete(@name)
141
+ class << self; undef :close; end
142
+ end
143
+ end
144
+
145
+ logger
146
+ end
147
+
148
+ # Access to the layouts.
149
+ #
150
+ def layouts
151
+ ::Logging::Layouts
152
+ end
153
+
154
+ # Access to the appenders.
155
+ #
156
+ def appenders
157
+ ::Logging::Appenders
158
+ end
159
+
160
+ # call-seq:
161
+ # Logging.consolidate( 'First::Name', 'Second::Name', ... )
162
+ #
163
+ # Consolidate all loggers under the given namespace. All child loggers
164
+ # in the namespace will use the "consolidated" namespace logger instead
165
+ # of creating a new logger for each class or module.
166
+ #
167
+ # If the "root" logger name is passed to this method then all loggers
168
+ # will consolidate to the root logger. In other words, only the root
169
+ # logger will be created, and it will be used by all classes and moduels
170
+ # in the applicaiton.
171
+ #
172
+ # ==== Example
173
+ #
174
+ # Logging.consolidate( 'Foo' )
175
+ #
176
+ # foo = Logging.logger['Foo']
177
+ # bar = Logging.logger['Foo::Bar']
178
+ # baz = Logging.logger['Baz']
179
+ #
180
+ # foo.object_id == bar.object_id #=> true
181
+ # foo.object_id == baz.object_id #=> false
182
+ #
183
+ def consolidate( *args )
184
+ ::Logging::Repository.instance.add_master(*args)
185
+ end
186
+
187
+ # call-seq:
188
+ # include Logging.globally
189
+ # include Logging.globally( :logger )
190
+ #
191
+ # Add a "logger" method to the including context. If included from
192
+ # Object or Kernel, the logger method will be available to all objects.
193
+ #
194
+ # Optionally, a method name can be given and that will be used to
195
+ # provided access to the logger:
196
+ #
197
+ # include Logging.globally( :log )
198
+ # log.info "Just using a shorter method name"
199
+ #
200
+ # If you prefer to use the shorter "log" to access the logger.
201
+ #
202
+ # ==== Example
203
+ #
204
+ # include Logging.globally
205
+ #
206
+ # class Foo
207
+ # logger.debug "Loading the Foo class"
208
+ # def initialize
209
+ # logger.info "Creating some new foo"
210
+ # end
211
+ # end
212
+ #
213
+ # logger.fatal "End of example"
214
+ #
215
+ def globally( name = :logger )
216
+ Module.new {
217
+ eval "def #{name}() @_logging_logger ||= ::Logging::Logger[self] end"
218
+ }
219
+ end
220
+
221
+ # call-seq:
222
+ # Logging.init( levels )
223
+ #
224
+ # Defines the levels available to the loggers. The _levels_ is an array
225
+ # of strings and symbols. Each element in the array is downcased and
226
+ # converted to a symbol; these symbols are used to create the logging
227
+ # methods in the loggers.
228
+ #
229
+ # The first element in the array is the lowest logging level. Setting the
230
+ # logging level to this value will enable all log messages. The last
231
+ # element in the array is the highest logging level. Setting the logging
232
+ # level to this value will disable all log messages except this highest
233
+ # level.
234
+ #
235
+ # This method should only be invoked once to configure the logging
236
+ # levels. It is automatically invoked with the default logging levels
237
+ # when the first logger is created.
238
+ #
239
+ # The levels "all" and "off" are reserved and will be ignored if passed
240
+ # to this method.
241
+ #
242
+ # Example:
243
+ #
244
+ # Logging.init :debug, :info, :warn, :error, :fatal
245
+ # log = Logging::Logger['my logger']
246
+ # log.level = :warn
247
+ # log.warn 'Danger! Danger! Will Robinson'
248
+ # log.info 'Just FYI' # => not logged
249
+ #
250
+ # or
251
+ #
252
+ # Logging.init %w(DEBUG INFO NOTICE WARNING ERR CRIT ALERT EMERG)
253
+ # log = Logging::Logger['syslog']
254
+ # log.level = :notice
255
+ # log.warning 'This is your first warning'
256
+ # log.info 'Just FYI' # => not logged
257
+ #
258
+ def init( *args )
259
+ args = %w(debug info warn error fatal) if args.empty?
260
+
261
+ args.flatten!
262
+ levels = LEVELS.clear
263
+ names = LNAMES.clear
264
+
265
+ id = 0
266
+ args.each do |lvl|
267
+ lvl = levelify lvl
268
+ unless levels.has_key?(lvl) or lvl == 'all' or lvl == 'off'
269
+ levels[lvl] = id
270
+ names[id] = lvl.upcase
271
+ id += 1
272
+ end
273
+ end
274
+
275
+ longest = names.inject {|x,y| (x.length > y.length) ? x : y}
276
+ longest = 'off' if longest.length < 3
277
+ module_eval "MAX_LEVEL_LENGTH = #{longest.length}", __FILE__, __LINE__
278
+
279
+ levels.keys
280
+ end
281
+
282
+ # call-seq:
283
+ # Logging.format_as( obj_format )
284
+ #
285
+ # Defines the default _obj_format_ method to use when converting objects
286
+ # into string representations for logging. _obj_format_ can be one of
287
+ # <tt>:string</tt>, <tt>:inspect</tt>, or <tt>:yaml</tt>. These
288
+ # formatting commands map to the following object methods
289
+ #
290
+ # * :string => to_s
291
+ # * :inspect => inspect
292
+ # * :yaml => to_yaml
293
+ #
294
+ # An +ArgumentError+ is raised if anything other than +:string+,
295
+ # +:inspect+, +:yaml+ is passed to this method.
296
+ #
297
+ def format_as( f )
298
+ f = f.intern if f.instance_of? String
299
+
300
+ unless [:string, :inspect, :yaml].include? f
301
+ raise ArgumentError, "unknown object format '#{f}'"
302
+ end
303
+
304
+ module_eval "OBJ_FORMAT = :#{f}", __FILE__, __LINE__
305
+ end
306
+
307
+ # call-seq:
308
+ # Logging.backtrace #=> true or false
309
+ # Logging.backtrace( value ) #=> true or false
310
+ #
311
+ # Without any arguments, returns the global exception backtrace logging
312
+ # value. When set to +true+ backtraces will be written to the logs; when
313
+ # set to +false+ backtraces will be suppressed.
314
+ #
315
+ # When an argument is given the global exception backtrace setting will
316
+ # be changed. Value values are <tt>"on"</tt>, <tt>:on<tt> and +true+ to
317
+ # turn on backtraces and <tt>"off"</tt>, <tt>:off</tt> and +false+ to
318
+ # turn off backtraces.
319
+ #
320
+ def backtrace( b = nil )
321
+ @backtrace = true unless defined? @backtrace
322
+ return @backtrace if b.nil?
323
+
324
+ @backtrace = case b
325
+ when :on, 'on', true; true
326
+ when :off, 'off', false; false
327
+ else
328
+ raise ArgumentError, "backtrace must be true or false"
329
+ end
330
+ end
331
+
332
+ # Returns the version string for the library.
333
+ #
334
+ def version
335
+ VERSION
336
+ end
337
+
338
+ # Returns the library path for the module. If any arguments are given,
339
+ # they will be joined to the end of the libray path using
340
+ # <tt>File.join</tt>.
341
+ #
342
+ def libpath( *args )
343
+ args.empty? ? LIBPATH : ::File.join(LIBPATH, args.flatten)
344
+ end
345
+
346
+ # Returns the lpath for the module. If any arguments are given,
347
+ # they will be joined to the end of the path using
348
+ # <tt>File.join</tt>.
349
+ #
350
+ def path( *args )
351
+ args.empty? ? PATH : ::File.join(PATH, args.flatten)
352
+ end
353
+
354
+ # call-seq:
355
+ # show_configuration( io = STDOUT, logger = 'root' )
356
+ #
357
+ # This method is used to show the configuration of the logging
358
+ # framework. The information is written to the given _io_ stream
359
+ # (defaulting to stdout). Normally the configuration is dumped starting
360
+ # with the root logger, but any logger name can be given.
361
+ #
362
+ # Each line contains information for a single logger and it's appenders.
363
+ # A child logger is indented two spaces from it's parent logger. Each
364
+ # line contains the logger name, level, additivity, and trace settings.
365
+ # Here is a brief example:
366
+ #
367
+ # root ........................... *info -T
368
+ # LoggerA ...................... info +A -T
369
+ # LoggerA::LoggerB ........... info +A -T
370
+ # LoggerA::LoggerC ........... *debug +A -T
371
+ # LoggerD ...................... *warn -A +T
372
+ #
373
+ # The lines can be deciphered as follows:
374
+ #
375
+ # 1) name - the name of the logger
376
+ #
377
+ # 2) level - the logger level; if it is preceeded by an
378
+ # asterisk then the level was explicitly set for that
379
+ # logger (as opposed to being inherited from the parent
380
+ # logger)
381
+ #
382
+ # 3) additivity - a "+A" shows the logger is additive, and log events
383
+ # will be passed up to the parent logger; "-A" shows
384
+ # that the logger will *not* pass log events up to the
385
+ # parent logger
386
+ #
387
+ # 4) trace - a "+T" shows that the logger will include trace
388
+ # information in generated log events (this includes
389
+ # filename and line number of the log message; "-T"
390
+ # shows that the logger does not include trace
391
+ # information in the log events)
392
+ #
393
+ # If a logger has appenders then they are listed, on per line,
394
+ # immediately below the logger. Appender lines are pre-pended with a
395
+ # single dash:
396
+ #
397
+ # root ........................... *info -T
398
+ # - <Appenders::Stdout:0x8b02a4 name="stdout">
399
+ # LoggerA ...................... info +A -T
400
+ # LoggerA::LoggerB ........... info +A -T
401
+ # LoggerA::LoggerC ........... *debug +A -T
402
+ # LoggerD ...................... *warn -A +T
403
+ # - <Appenders::Stderr:0x8b04ca name="stderr">
404
+ #
405
+ # We can see in this configuration dump that all the loggers will append
406
+ # to stdout via the Stdout appender configured in the root logger. All
407
+ # the loggers are additive, and so their generated log events will be
408
+ # passed up to the root logger.
409
+ #
410
+ # The exception in this configuration is LoggerD. Its additivity is set
411
+ # to false. It uses its own appender to send messages to stderr.
412
+ #
413
+ def show_configuration( io = STDOUT, logger = 'root', indent = 0 )
414
+ logger = ::Logging::Logger[logger] unless ::Logging::Logger === logger
415
+
416
+ logger._dump_configuration(io, indent)
417
+
418
+ indent += 2
419
+ children = ::Logging::Repository.instance.children(logger.name)
420
+ children.sort {|a,b| a.name <=> b.name}.each do |child|
421
+ ::Logging.show_configuration(io, child, indent)
422
+ end
423
+
424
+ nil
425
+ end
426
+
427
+ # :stopdoc:
428
+ # Convert the given level into a connaconical form - a lowercase string.
429
+ def levelify( level )
430
+ case level
431
+ when String; level.downcase
432
+ when Symbol; level.to_s.downcase
433
+ else raise ArgumentError, "levels must be a String or Symbol" end
434
+ end
435
+
436
+ # Convert the given level into a level number.
437
+ def level_num( level )
438
+ l = levelify level
439
+ case l
440
+ when 'all'; 0
441
+ when 'off'; LEVELS.length
442
+ else begin; Integer(l); rescue ArgumentError; LEVELS[l] end end
443
+ end
444
+
445
+ # Internal logging method for use by the framework.
446
+ def log_internal( level = 1, &block )
447
+ ::Logging::Logger[::Logging].__send__(levelify(LNAMES[level]), &block)
448
+ end
449
+
450
+ # Close all appenders
451
+ def shutdown
452
+ log_internal {'shutdown called - closing all appenders'}
453
+ ::Logging::Appenders.each {|appender| appender.close}
454
+ end
455
+ # :startdoc:
456
+ end
457
+ end # module Logging
458
+
459
+ require Logging.libpath(%w[logging layout])
460
+ require Logging.libpath(%w[logging log_event])
461
+ require Logging.libpath(%w[logging logger])
462
+ require Logging.libpath(%w[logging repository])
463
+ require Logging.libpath(%w[logging root_logger])
464
+ require Logging.libpath(%w[logging stats])
465
+ require Logging.libpath(%w[logging appenders])
466
+ require Logging.libpath(%w[logging layouts])
467
+
468
+ require Logging.libpath(%w[logging config configurator])
469
+ require Logging.libpath(%w[logging config yaml_configurator])
470
+
471
+ unless defined? Logging::EXIT
472
+ # This exit handler will close all the appenders that exist in the system.
473
+ # This is needed for closing IO streams and connections to the syslog server
474
+ # or e-mail servers, etc.
475
+ #
476
+ at_exit {Logging.shutdown}
477
+ Logging::EXIT = true
478
+ end # unless defined?
479
+ # EOF