log4ruby 0.0.3 → 0.0.4

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,57 +1,64 @@
1
- #
2
- # 21 Jul 2012
3
- #
4
-
5
- module Log4Ruby
6
-
7
- # Base class for appenders.
8
- class Appender
9
-
10
- # Set the formatter this appender uses.
11
- attr_writer :formatter
12
-
13
- # New appender. This class should be treated as an abstract base class and should not be initialised directly.
14
- #
15
- # @param [Log4Ruby::Level] level the threshold level for the appender.
16
- # @param [Log4Ruby::Formatter] formatter the formatter the appender uses.
17
- def initialize(level, formatter)
18
- @level = level
19
- @formatter = formatter
20
- @closed = false
21
- end
22
-
23
- # Closes this appender. Logs will not be emitted by this appender any longer.
24
- #
25
- # @return [TrueClass] Always true.
26
- def close
27
- @closed = true
28
- end
29
-
30
- # Check if this appender is closed.
31
- #
32
- # @return [TrueClass, FalseClass] true if the appender is closed.
33
- def closed?
34
- @closed
35
- end
36
-
37
- # Process the log item.
38
- #
39
- # @param [Log4Ruby::Log] log
40
- def process_log(log)
41
- return if log[:level] < @level
42
-
43
- # Format the log item and emit it.
44
- emit(@formatter.format(log))
45
- end
46
-
47
- private
48
-
49
- # Emits a log message to this appenders target.
50
- #
51
- # @param [String] message the message to emit.
52
- def emit(message)
53
- end
54
-
55
- end
56
-
1
+ #
2
+ # 21 Jul 2012
3
+ #
4
+
5
+ require "log4ruby/formatters/default_formatter"
6
+
7
+ module Log4Ruby
8
+
9
+ # Base class for appenders.
10
+ class Appender
11
+
12
+ # Set the formatter this appender uses.
13
+ attr_writer :formatter
14
+
15
+ # New appender. This class should be treated as an abstract base class and should not be initialised directly.
16
+ #
17
+ # @param [Log4Ruby::Level] level the threshold level for the appender.
18
+ # @param [Hash] options configuration options. Supported keys are:
19
+ # :formatter - the formatter this appender should use. Uses the DefaultFormatter if not specified.
20
+ def initialize(level, options = {})
21
+ @level = level
22
+ @formatter = get_option(options, :formatter, false, DefaultFormatter.new)
23
+ @closed = false
24
+
25
+ at_exit { close }
26
+ end
27
+
28
+ # Closes this appender. Logs will not be emitted by this appender any longer.
29
+ # If the appender is already closed, this method should not do anything.
30
+ #
31
+ # @return [TrueClass] Always true.
32
+ def close
33
+ @closed = true
34
+ end
35
+
36
+ # Check if this appender is closed.
37
+ #
38
+ # @return [TrueClass, FalseClass] true if the appender is closed.
39
+ def closed?
40
+ @closed
41
+ end
42
+
43
+ # Process the log item.
44
+ #
45
+ # @param [Log4Ruby::Log] log
46
+ def process_log(log)
47
+ return if self.closed?
48
+ return if log[:level] < @level
49
+
50
+ # Format the log item and emit it.
51
+ emit(@formatter.format(log))
52
+ end
53
+
54
+ private
55
+
56
+ # Emits a log message to this appenders target.
57
+ #
58
+ # @param [String] message the message to emit.
59
+ def emit(message)
60
+ end
61
+
62
+ end
63
+
57
64
  end
@@ -13,10 +13,16 @@ module Log4Ruby
13
13
 
14
14
  # New console appender.
15
15
  #
16
- # @param [Symbol] target either stdout or stderr.
17
- def initialize(level, formatter, target = :stdout)
16
+ # @param [Log4Ruby::Level] level the threshold level for the appender.
17
+ # @param [Hash] options configuration options. Supported keys are:
18
+ # :formatter - the formatter this appender should use. Uses the DefaultFormatter if not specified.
19
+ # :target - the target stream to use (:stdout or :stderr). Default is :stdout
20
+ def initialize(level, options = {})
21
+ target = get_option(options, :target, false, :stdout)
18
22
  raise ArgumentError.new("Invalid target '#{target}'. Must be either 'stdout' or 'stderr'.") unless TARGETS.has_key?(target)
19
- super(level, formatter, TARGETS[target])
23
+
24
+ set_option(options, :stream, TARGETS[target], true)
25
+ super(level, options)
20
26
  end
21
27
 
22
28
  end
@@ -3,6 +3,7 @@
3
3
  #
4
4
 
5
5
  require "date"
6
+ require "fileutils"
6
7
 
7
8
  require "log4ruby/appenders/stream_appender"
8
9
 
@@ -32,6 +33,7 @@ module Log4Ruby
32
33
  # New stream appender.
33
34
  #
34
35
  # @param [Hash] options configuration hash. Supports the following parameters.
36
+ # :formatter - the formatter this appender should use. Uses the DefaultFormatter if not specified.
35
37
  # :directory - the directory into which the logs should be saved. Defaults to the current directory.
36
38
  # :prefix - the file name prefix for the log files. *required*
37
39
  # :suffix - the file name suffix for the log files. Defaults to 'log'
@@ -51,8 +53,9 @@ module Log4Ruby
51
53
  # roll_using_date:
52
54
  # :frequency - the frequency with which to roll files (:hourly, :daily, :weekly, :monthly, :yearly).
53
55
  # Default is :daily.
54
- def initialize(level, formatter, options = {})
55
- super(level, formatter, nil)
56
+ def initialize(level, options = {})
57
+ set_option(options, :stream, nil, true)
58
+ super(level, options)
56
59
 
57
60
  @directory = get_option(options, :directory, false, "./")
58
61
  @prefix = get_option(options, :prefix, true)
@@ -106,9 +109,12 @@ module Log4Ruby
106
109
  # Create the emit method that will roll using the file date as the trigger.
107
110
  class << self
108
111
  self
109
- end.send(:define_method, :emit) do |message|
110
- roll_using_date
111
- super(message)
112
+
113
+ # Override to roll using the date of the file.
114
+ def emit(message)
115
+ roll_using_date
116
+ super(message)
117
+ end
112
118
  end
113
119
  end
114
120
 
@@ -122,9 +128,12 @@ module Log4Ruby
122
128
  # Create the emit method that will roll using the file size as the trigger.
123
129
  class << self
124
130
  self
125
- end.send(:define_method, :emit) do |message|
126
- roll_using_size
127
- super(message)
131
+
132
+ # Override to roll using the size of the file.
133
+ def emit(message)
134
+ roll_using_size
135
+ super(message)
136
+ end
128
137
  end
129
138
  end
130
139
 
@@ -1,16 +1,25 @@
1
- #
2
- # 21 Jul 2012
3
- #
4
-
5
- module Log4Ruby
6
-
7
- # An appender that does nothing. All logs to it are ignored and just consumed.
8
- class NilAppender
9
-
10
- # Don't do anything with the log. Just return.
11
- def process_log(log)
12
- end
13
-
14
- end
15
-
1
+ #
2
+ # 21 Jul 2012
3
+ #
4
+
5
+ require "log4ruby/appender"
6
+
7
+ module Log4Ruby
8
+
9
+ # An appender that does nothing. All logs to it are ignored and just consumed.
10
+ class NilAppender < Log4Ruby::Appender
11
+
12
+ # New NilAppender. Does nothing.
13
+ #
14
+ # @param [Log4Ruby::Level] level - not used.
15
+ # @param [Hash] options - not used.
16
+ def initialize(level, options = {})
17
+ end
18
+
19
+ # Don't do anything with the log. Just return.
20
+ def process_log(log)
21
+ end
22
+
23
+ end
24
+
16
25
  end
@@ -1,31 +1,65 @@
1
- #
2
- # 21 Jul 2012
3
- #
4
-
5
- require "log4ruby/appender"
6
-
7
- module Log4Ruby
8
-
9
- # Simple appender that can emit to a stream (file, console, socket, etc i.e. anything that responds to the write method)
10
- class StreamAppender < Log4Ruby::Appender
11
-
12
- # New stream appender.
13
- #
14
- # @param [IO] stream a IO stream that can respond to the write method.
15
- def initialize(level, formatter, stream)
16
- super(level, formatter)
17
- @stream = stream
18
- end
19
-
20
- private
21
-
22
- # Writes the message to the underlying stream.
23
- #
24
- # @param [String] message the message to write.
25
- def emit(message)
26
- @stream.write(message)
27
- end
28
-
29
- end
30
-
31
- end
1
+ #
2
+ # 21 Jul 2012
3
+ #
4
+
5
+ require "log4ruby/appender"
6
+
7
+ module Log4Ruby
8
+
9
+ # Simple appender that can emit to a stream (file, console, socket, etc i.e. anything that responds to the write method)
10
+ class StreamAppender < Log4Ruby::Appender
11
+
12
+ # New stream appender.
13
+ #
14
+ # @param [Log4Ruby::Level] level the threshold level for the appender.
15
+ # @param [Hash] options configuration options. Supported keys are:
16
+ # :formatter - the formatter this appender should use. Uses the DefaultFormatter if not specified.
17
+ # :stream - the stream this appender should log to. *required*.
18
+ def initialize(level, options = {})
19
+ super(level, options)
20
+ @stream = get_option(options, :stream)
21
+ @emit_header = true
22
+ end
23
+
24
+ # Overridden to emit the footer. If closed, does nothing.
25
+ def close
26
+ emit_footer unless @closed
27
+ @stream.close unless (@stream.nil? or @stream.closed?)
28
+
29
+ super
30
+ end
31
+
32
+ # Register a block that will serve as the callback for when the footer needs to be generated.
33
+ def footer(&block)
34
+ @footer = block
35
+ end
36
+
37
+ # Register a block that will serve as the callback for when the header needs to be generated.
38
+ def header(&block)
39
+ @header = block
40
+ end
41
+
42
+ private
43
+
44
+ # Emits the footer to the appender's target. This will be executed just before the appender is closed.
45
+ def emit_footer
46
+ @footer.call(@stream) unless @footer.nil?
47
+ end
48
+
49
+ # Emits the header to the appender's target. This will be executed just before the first line is emitted.
50
+ def emit_header
51
+ @header.call(@stream) unless @header.nil?
52
+ @emit_header = false
53
+ end
54
+
55
+ # Writes the message to the underlying stream.
56
+ #
57
+ # @param [String] message the message to write.
58
+ def emit(message)
59
+ emit_header if @emit_header
60
+ @stream.write(message)
61
+ end
62
+
63
+ end
64
+
65
+ end
@@ -0,0 +1,23 @@
1
+ #
2
+ # 25 Jul 2012
3
+ #
4
+
5
+ require "log4ruby/formatter"
6
+
7
+ module Log4Ruby
8
+
9
+ # Default formatter for Log4Ruby.
10
+ class DefaultFormatter < Log4Ruby::Formatter
11
+
12
+ # Format a log item.
13
+ #
14
+ # @param [Log4Ruby::Log] log
15
+ #
16
+ # @return [String] the fully formatted log message.
17
+ def format(log)
18
+ "#{log[:level].name} - #{log[:message]}\n"
19
+ end
20
+
21
+ end
22
+
23
+ end
@@ -1,81 +1,80 @@
1
- #
2
- # 21 Jul 2012
3
- #
4
-
5
- require "log4ruby/formatter"
6
- require "log4ruby/log"
7
-
8
- module Log4Ruby
9
-
10
- class PatternFormatter
11
-
12
- # New pattern formatter.
13
- #
14
- # @param [String] format_string the pattern string to use when formatting log messages.
15
- # @param [Array] subst_array the log parameters to substitute into the format string.
16
- # @param [Hash] parameter_formatters custom formatters for log parameters. Maps parameter names to callable objects
17
- # that will be invoked with the parameter's value. The values returned will be used when substituting into the
18
- # format string.
19
- #
20
- # e.g.
21
- # format_string = [%s] %7s - %s : %s
22
- # subst_array = [:timestamp, :level, :full_logger_name, :message]
23
- # custom_formatters = {:timestamp => Proc.new { |value| value.strftime("%Y-%m-%d %H:%M:%S.%L") }}
24
- #
25
- # The above example will print the timestamp in the format specified.
26
- # The level will be right aligned padded on the left to use 7 spaces followed by the full logger name and the
27
- # message.
28
- def initialize(format_string, subst_array, parameter_formatters = {})
29
- @format_string = format_string
30
- @subst_array = subst_array
31
- @parameter_formatters = parameter_formatters
32
- end
33
-
34
- # Adds a parameter formatter to this formatter.
35
- #
36
- # @param [Symbol] parameter the parameter to format.
37
- # @param [Proc] callable the callable to invoke.
38
- def add_parameter_formatter(parameter, callable)
39
- @parameter_formatters[parameter] = callable
40
- end
41
-
42
- # Format the log item using the pattern string.
43
- #
44
- # @param [Log4Ruby::Log] log the log to format.
45
- #
46
- # @return [String] the fully formatted log message.
47
- def format(log)
48
- # Get the values of the parameters (apply custom formatters too).
49
- parameters = @subst_array.map do |parameter|
50
- value = log[parameter]
51
- @parameter_formatters.has_key?(parameter) ? @parameter_formatters[parameter].call(value) : value.to_s
52
- end
53
- # Substitute into the format string.
54
- @format_string % parameters
55
- end
56
-
57
- end
58
-
59
- # Some common parameter formatters to use with the pattern formatter.
60
- class ParameterFormatters
61
-
62
- # Returns a logger formatter that will format logger objects.
63
- #
64
- # @param [Integer] index an integer that represents how far up the tree the logger's name should be resolved. So
65
- # 1 would be only the name of the logger, 2 would be the name of the logger's parent and the name of the logger,
66
- # and so on...
67
- def self.logger_formatter(index)
68
- start = 0 - index
69
- Proc.new { |logger| logger.full_name.split(".")[start..-1].join(".") }
70
- end
71
-
72
- # Returns a timestamp formatter that will format time objects using the specified format string.
73
- #
74
- # @param [String] format_string the format string.
75
- def self.timestamp_formatter(format_string)
76
- Proc.new { |timestamp| timestamp.strftime(format_string) }
77
- end
78
-
79
- end
80
-
81
- end
1
+ #
2
+ # 21 Jul 2012
3
+ #
4
+
5
+ require "log4ruby/formatter"
6
+ require "log4ruby/log"
7
+
8
+ module Log4Ruby
9
+
10
+ class PatternFormatter
11
+
12
+ # New pattern formatter.
13
+ #
14
+ # @param [String] format_string the pattern string to use when formatting log messages.
15
+ # @param [Array] subst_array the log parameters to substitute into the format string.
16
+ # @param [Hash] parameter_formatters custom formatters for log parameters. Maps parameter names to callable objects
17
+ # that will be invoked with the parameter's value. The values returned will be used when substituting into the
18
+ # format string.
19
+ #
20
+ # e.g.
21
+ # format_string = [%s] %7s - %s : %s
22
+ # subst_array = [:timestamp, :level, :full_logger_name, :message]
23
+ #
24
+ # The above example will print the timestamp in the format specified.
25
+ # The level will be right aligned padded on the left to use 7 spaces followed by the full logger name and the
26
+ # message.
27
+ def initialize(format_string, subst_array, parameter_formatters = {})
28
+ @format_string = format_string
29
+ @subst_array = subst_array
30
+ @parameter_formatters = parameter_formatters
31
+ end
32
+
33
+ # Adds a parameter formatter to this formatter.
34
+ #
35
+ # @param [Symbol] parameter the parameter to format.
36
+ # @param [Proc] callable the callable to invoke.
37
+ def add_parameter_formatter(parameter, callable)
38
+ @parameter_formatters[parameter] = callable
39
+ end
40
+
41
+ # Format the log item using the pattern string.
42
+ #
43
+ # @param [Log4Ruby::Log] log the log to format.
44
+ #
45
+ # @return [String] the fully formatted log message.
46
+ def format(log)
47
+ # Get the values of the parameters (apply custom formatters too).
48
+ parameters = @subst_array.map do |parameter|
49
+ value = log[parameter]
50
+ @parameter_formatters.has_key?(parameter) ? @parameter_formatters[parameter].call(value) : value.to_s
51
+ end
52
+ # Substitute into the format string.
53
+ @format_string % parameters
54
+ end
55
+
56
+ end
57
+
58
+ # Some common parameter formatters to use with the pattern formatter.
59
+ class ParameterFormatters
60
+
61
+ # Returns a logger formatter that will format logger objects.
62
+ #
63
+ # @param [Integer] index an integer that represents how far up the tree the logger's name should be resolved. So
64
+ # 1 would be only the name of the logger, 2 would be the name of the logger's parent and the name of the logger,
65
+ # and so on...
66
+ def self.logger_formatter(index)
67
+ start = 0 - index
68
+ Proc.new { |logger| logger.full_name.split(".")[start..-1].join(".") }
69
+ end
70
+
71
+ # Returns a timestamp formatter that will format time objects using the specified format string.
72
+ #
73
+ # @param [String] format_string the format string.
74
+ def self.timestamp_formatter(format_string)
75
+ Proc.new { |timestamp| timestamp.strftime(format_string) }
76
+ end
77
+
78
+ end
79
+
80
+ end
@@ -1,95 +1,95 @@
1
- #
2
- # 21 Jul 2012
3
- #
4
-
5
- require "log4ruby/logger"
6
-
7
- module Log4Ruby
8
-
9
- class Level
10
-
11
- # Creates a new level with the specified name and weight. Only level's created using this method are
12
- # automatically made available on the Logger class. Any other level's will have to be handled manually.
13
- # The method with which it is made available is the same as the level, but with all lowercase characters.
14
- #
15
- # @param [String] name the name of the new level. Will overwrite an existing level with the same name, if it exists.
16
- # The name is converted to all uppercase characters.
17
- # @param [Float] weight the weight of the level. Higher the weight, higher the priority.
18
- def self.register(name, weight)
19
- name = name.upcase
20
- method_name = name.downcase
21
- query_method_name = "#{method_name}?"
22
- level = Level.new(name, weight)
23
- const_set(name, level)
24
- # Create the logging method.
25
- Logger.send(:define_method, method_name) do |message, parameters = {}|
26
- return if self.closed?
27
- return if level < self.effective_level
28
- # Construct the log and dispatch it.
29
- parameters[:message] = message
30
- parameters[:level] = level
31
- parameters[:logger] = self
32
- self.process_log(Log.new(parameters))
33
- end
34
- # Create the query method - for checking the effective level of a logger / appender.
35
- Logger.send(:define_method, query_method_name) { self.effective_level <= level }
36
- Appender.send(:define_method, query_method_name) { self.level <= level }
37
- end
38
-
39
- # Parses the specified string in an attempt to convert it to a Level object.
40
- #
41
- # @param [String] name the name of the level.
42
- #
43
- # @return [Log4Ruby::Level] the level object.
44
- def self.parse(name)
45
- name = name.upcase
46
- const_get(name)
47
- end
48
-
49
- # The weight of this level. Higher the value, more severe the log.
50
- attr_reader :weight
51
- # The name of the level.
52
- attr_reader :name
53
-
54
- # Creates a new level.
55
- #
56
- # @param [String] name the name of the level.
57
- # @param [Float] weight the weight for this level. Higher the weight, higher the severity.
58
- def initialize(name, weight)
59
- @name = name
60
- @weight = weight
61
- end
62
-
63
- # Check if this level is less than the specified other log level.
64
- # Comparison is done using the weight attribute
65
- def <(other)
66
- self.weight < other.weight
67
- end
68
-
69
- # Check if this level is less than or equal to the specified other log level.
70
- # Comparison is done using the weight attribute
71
- def <=(other)
72
- self.weight <= other.weight
73
- end
74
-
75
- # Override to return the name of the level.
76
- #
77
- # @return [String] the level's name.
78
- def to_s
79
- @name
80
- end
81
-
82
- register("ALL", Float::MIN)
83
- register("TRACE", 100.0)
84
- register("FINE", 200.0)
85
- register("DEBUG", 300.0)
86
- register("CONF", 400.0)
87
- register("INFO", 500.0)
88
- register("WARN", 600.0)
89
- register("ERROR", 700.0)
90
- register("FATAL", 800.0)
91
- register("OFF", Float::MAX)
92
-
93
- end
94
-
1
+ #
2
+ # 21 Jul 2012
3
+ #
4
+
5
+ require "log4ruby/logger"
6
+
7
+ module Log4Ruby
8
+
9
+ class Level
10
+
11
+ # Creates a new level with the specified name and weight. Only level's created using this method are
12
+ # automatically made available on the Logger class. Any other level's will have to be handled manually.
13
+ # The method with which it is made available is the same as the level, but with all lowercase characters.
14
+ #
15
+ # @param [String] name the name of the new level. Will overwrite an existing level with the same name, if it exists.
16
+ # The name is converted to all uppercase characters.
17
+ # @param [Float] weight the weight of the level. Higher the weight, higher the priority.
18
+ def self.register(name, weight)
19
+ name = name.upcase
20
+ method_name = name.downcase
21
+ query_method_name = "#{method_name}?"
22
+ level = Level.new(name, weight)
23
+ const_set(name, level)
24
+ # Create the logging method.
25
+ Logger.send(:define_method, method_name) do |message, parameters = {}|
26
+ return if self.closed?
27
+ return if level < self.effective_level
28
+ # Construct the log and dispatch it.
29
+ parameters[:message] = message
30
+ parameters[:level] = level
31
+ parameters[:logger] = self
32
+ self.process_log(Log.new(parameters))
33
+ end
34
+ # Create the query method - for checking the effective level of a logger / appender.
35
+ Logger.send(:define_method, query_method_name) { self.effective_level <= level }
36
+ Appender.send(:define_method, query_method_name) { self.level <= level }
37
+ end
38
+
39
+ # Parses the specified string in an attempt to convert it to a Level object.
40
+ #
41
+ # @param [String] name the name of the level.
42
+ #
43
+ # @return [Log4Ruby::Level] the level object.
44
+ def self.parse(name)
45
+ name = name.upcase
46
+ const_get(name)
47
+ end
48
+
49
+ # The weight of this level. Higher the value, more severe the log.
50
+ attr_reader :weight
51
+ # The name of the level.
52
+ attr_reader :name
53
+
54
+ # Creates a new level.
55
+ #
56
+ # @param [String] name the name of the level.
57
+ # @param [Float] weight the weight for this level. Higher the weight, higher the severity.
58
+ def initialize(name, weight)
59
+ @name = name
60
+ @weight = weight
61
+ end
62
+
63
+ # Check if this level is less than the specified other log level.
64
+ # Comparison is done using the weight attribute
65
+ def <(other)
66
+ self.weight < other.weight
67
+ end
68
+
69
+ # Check if this level is less than or equal to the specified other log level.
70
+ # Comparison is done using the weight attribute
71
+ def <=(other)
72
+ self.weight <= other.weight
73
+ end
74
+
75
+ # Override to return the name of the level.
76
+ #
77
+ # @return [String] the level's name.
78
+ def to_s
79
+ @name
80
+ end
81
+
82
+ register("ALL", Float::MIN)
83
+ register("TRACE", 100.0)
84
+ register("FINE", 200.0)
85
+ register("DEBUG", 300.0)
86
+ register("CONF", 400.0)
87
+ register("INFO", 500.0)
88
+ register("WARN", 600.0)
89
+ register("ERROR", 700.0)
90
+ register("FATAL", 800.0)
91
+ register("OFF", Float::MAX)
92
+
93
+ end
94
+
95
95
  end
@@ -1,148 +1,148 @@
1
- #
2
- # 22 Jul 2012
3
- #
4
-
5
- require "singleton"
6
-
7
- module Log4Ruby
8
-
9
- # Represents a logger.
10
- # Loggers are arranged into a tree, where each logger, after having dispatched the log to its appenders,
11
- # forwards the log to its parents too.
12
- class Logger
13
-
14
- # The effective level of this logger. This will be the parent's effective level if a level has not been
15
- # explicitly set for this logger.
16
- attr_reader :effective_level
17
- # The full name of this logger.
18
- attr_reader :full_name
19
- # The name of this logger.
20
- attr_reader :name
21
- # True to use parent appenders (the default) false to use only this logger's appenders.
22
- attr_writer :use_parent_appenders
23
-
24
- # Creates a new logger. Users should not use this method, and should use the Log4Ruby.get_logger method.
25
- #
26
- # @param [String] name the name for this logger.
27
- # @param [Log4Ruby::Logger] parent the parent to this logger. If set to nil, becomes the child of the root logger.
28
- # @param [Log4Ruby::Level] level the level of this logger. If set to nil, uses the parent's effective level
29
- # (defaults to DEBUG for the root logger).
30
- # @param [Array] appenders a list of appenders this logger will use.
31
- def initialize(name, parent = nil, level = nil, appenders = [])
32
- @name = name
33
- @parent = parent.nil? ? RootLogger.instance : parent
34
- @level = level
35
- @appenders = appenders
36
- @children = {}
37
- @closed = false
38
-
39
- @use_parent_appenders = true
40
- @full_name = @parent.kind_of?(RootLogger) ? @name : @parent.full_name + "." + @name
41
- @effective_level = level.nil? ? @parent.effective_level : level
42
- end
43
-
44
- # Adds an appender to this logger.
45
- #
46
- # @param [Log4Ruby::Appender] appender the appender to add.
47
- def add_appender(appender)
48
- @appenders << appender
49
- end
50
-
51
- # Shuts down this logger. It will no longer dispatch logs to its appenders, not will it forward logs to its parent.
52
- #
53
- # @return [TrueClass] Always true.
54
- def close
55
- @closed = true
56
- end
57
-
58
- # Check if this logger is closed.
59
- #
60
- # @return [TrueClass, FalseClass] true if the logger is closed.
61
- def closed?
62
- @closed
63
- end
64
-
65
- # Gets a child logger with the specified name. If the create flag is true, it will create a new logger
66
- # with this name.
67
- #
68
- # @param [String] name the name of the logger.
69
- # @param [TrueClass, FalseClass] create if true, create a logger if it does not exist.
70
- def get_logger(name, create = false)
71
- if @children.has_key?(name)
72
- @children[name]
73
- elsif create
74
- @children[name] = Logger.new(name, self)
75
- else
76
- raise Log4Ruby::LoggerNotFoundError.new("Logger '#{name}' does not exist under '#@full_name'!")
77
- end
78
- end
79
-
80
- # Update this logger's level. This will update the effective level for all child loggers too (except for the ones
81
- # that have had their level explicitly set.
82
- #
83
- # @param [Log4Ruby::Level] new_level the new level.
84
- def set_level(new_level)
85
- @level = new_level
86
- @effective_level = new_level
87
- @children.each_value { |logger| logger.update_effective_level(new_level) }
88
- end
89
-
90
- # Returns the full name of the logger.
91
- #
92
- # @return [String] the full name of the logger.
93
- def to_s
94
- @full_name
95
- end
96
-
97
- protected
98
-
99
- # Updates the effective level for this logger. This method is called internally when a logger's level is updated
100
- # and should not be invoked directly.
101
- #
102
- # @param [Log4Ruby::Level] new_level the new effective level.
103
- def update_effective_level(new_level)
104
- if @level.nil?
105
- @effective_level = new_level
106
- @children.each_value { |logger| logger.update_effective_level(new_level) }
107
- end
108
- end
109
-
110
- # Process the log message.
111
- #
112
- # @param [Log4Ruby::Log] log the log item to process. Does nothing if the log does not meet this logger's
113
- # threshold level.
114
- def process_log(log)
115
- return if self.closed?
116
- return if log[:level] < self.effective_level
117
- # Forward to each appender. Once done, send to the parent.
118
- @appenders.each { |appender| appender.process_log(log) }
119
- @parent.process_log(log) if @use_parent_appenders
120
- end
121
-
122
- end
123
-
124
- # Represents the root logger. This logger is similar to any other logger, except since it does not have a parent
125
- # logger, it does not forward logs.
126
- class RootLogger < Logger
127
-
128
- include Singleton
129
-
130
- # New root logger. The root logger is the parent of all loggers in the system.
131
- def initialize
132
- @full_name = @name = "Root"
133
- @parent = nil
134
- @effective_level = @level = Log4Ruby::Level::DEBUG
135
- @appenders = []
136
- @children = {}
137
- @use_parent_appenders = false
138
- end
139
-
140
- # Override to do nothing. Since the root doesn't have a parent.
141
- #
142
- # @param [Log4Ruby::Level] new_level ignored, since the root doesn't have a parent.
143
- def use_parent_appenders=(new_level)
144
- end
145
-
146
- end
147
-
1
+ #
2
+ # 22 Jul 2012
3
+ #
4
+
5
+ require "singleton"
6
+
7
+ module Log4Ruby
8
+
9
+ # Represents a logger.
10
+ # Loggers are arranged into a tree, where each logger, after having dispatched the log to its appenders,
11
+ # forwards the log to its parents too.
12
+ class Logger
13
+
14
+ # The effective level of this logger. This will be the parent's effective level if a level has not been
15
+ # explicitly set for this logger.
16
+ attr_reader :effective_level
17
+ # The full name of this logger.
18
+ attr_reader :full_name
19
+ # The name of this logger.
20
+ attr_reader :name
21
+ # True to use parent appenders (the default) false to use only this logger's appenders.
22
+ attr_writer :use_parent_appenders
23
+
24
+ # Creates a new logger. Users should not use this method, and should use the Log4Ruby.get_logger method.
25
+ #
26
+ # @param [String] name the name for this logger.
27
+ # @param [Log4Ruby::Logger] parent the parent to this logger. If set to nil, becomes the child of the root logger.
28
+ # @param [Log4Ruby::Level] level the level of this logger. If set to nil, uses the parent's effective level
29
+ # (defaults to DEBUG for the root logger).
30
+ # @param [Array] appenders a list of appenders this logger will use.
31
+ def initialize(name, parent = nil, level = nil, appenders = [])
32
+ @name = name
33
+ @parent = parent.nil? ? RootLogger.instance : parent
34
+ @level = level
35
+ @appenders = appenders
36
+ @children = {}
37
+ @closed = false
38
+
39
+ @use_parent_appenders = true
40
+ @full_name = @parent.kind_of?(RootLogger) ? @name : @parent.full_name + "." + @name
41
+ @effective_level = level.nil? ? @parent.effective_level : level
42
+ end
43
+
44
+ # Adds an appender to this logger.
45
+ #
46
+ # @param [Log4Ruby::Appender] appender the appender to add.
47
+ def add_appender(appender)
48
+ @appenders << appender
49
+ end
50
+
51
+ # Shuts down this logger. It will no longer dispatch logs to its appenders, not will it forward logs to its parent.
52
+ #
53
+ # @return [TrueClass] Always true.
54
+ def close
55
+ @closed = true
56
+ end
57
+
58
+ # Check if this logger is closed.
59
+ #
60
+ # @return [TrueClass, FalseClass] true if the logger is closed.
61
+ def closed?
62
+ @closed
63
+ end
64
+
65
+ # Gets a child logger with the specified name. If the create flag is true, it will create a new logger
66
+ # with this name.
67
+ #
68
+ # @param [String] name the name of the logger.
69
+ # @param [TrueClass, FalseClass] create if true, create a logger if it does not exist.
70
+ def get_logger(name, create = false)
71
+ if @children.has_key?(name)
72
+ @children[name]
73
+ elsif create
74
+ @children[name] = Logger.new(name, self)
75
+ else
76
+ raise Log4Ruby::LoggerNotFoundError.new("Logger '#{name}' does not exist under '#@full_name'!")
77
+ end
78
+ end
79
+
80
+ # Update this logger's level. This will update the effective level for all child loggers too (except for the ones
81
+ # that have had their level explicitly set.
82
+ #
83
+ # @param [Log4Ruby::Level] new_level the new level.
84
+ def set_level(new_level)
85
+ @level = new_level
86
+ @effective_level = new_level
87
+ @children.each_value { |logger| logger.update_effective_level(new_level) }
88
+ end
89
+
90
+ # Returns the full name of the logger.
91
+ #
92
+ # @return [String] the full name of the logger.
93
+ def to_s
94
+ @full_name
95
+ end
96
+
97
+ protected
98
+
99
+ # Updates the effective level for this logger. This method is called internally when a logger's level is updated
100
+ # and should not be invoked directly.
101
+ #
102
+ # @param [Log4Ruby::Level] new_level the new effective level.
103
+ def update_effective_level(new_level)
104
+ if @level.nil?
105
+ @effective_level = new_level
106
+ @children.each_value { |logger| logger.update_effective_level(new_level) }
107
+ end
108
+ end
109
+
110
+ # Process the log message.
111
+ #
112
+ # @param [Log4Ruby::Log] log the log item to process. Does nothing if the log does not meet this logger's
113
+ # threshold level.
114
+ def process_log(log)
115
+ return if self.closed?
116
+ return if log[:level] < self.effective_level
117
+ # Forward to each appender. Once done, send to the parent.
118
+ @appenders.each { |appender| appender.process_log(log) }
119
+ @parent.process_log(log) if @use_parent_appenders
120
+ end
121
+
122
+ end
123
+
124
+ # Represents the root logger. This logger is similar to any other logger, except since it does not have a parent
125
+ # logger, it does not forward logs.
126
+ class RootLogger < Logger
127
+
128
+ include Singleton
129
+
130
+ # New root logger. The root logger is the parent of all loggers in the system.
131
+ def initialize
132
+ @full_name = @name = "Root"
133
+ @parent = nil
134
+ @effective_level = @level = Log4Ruby::Level::DEBUG
135
+ @appenders = []
136
+ @children = {}
137
+ @use_parent_appenders = false
138
+ end
139
+
140
+ # Override to do nothing. Since the root doesn't have a parent.
141
+ #
142
+ # @param [Log4Ruby::Level] new_level ignored, since the root doesn't have a parent.
143
+ def use_parent_appenders=(new_level)
144
+ end
145
+
146
+ end
147
+
148
148
  end
@@ -1,9 +1,9 @@
1
- #
2
- # 21 Jul 2012
3
- #
4
-
5
- module Log4Ruby
6
-
7
- VERSION = "0.0.3"
8
-
1
+ #
2
+ # 21 Jul 2012
3
+ #
4
+
5
+ module Log4Ruby
6
+
7
+ VERSION = "0.0.4"
8
+
9
9
  end
data/lib/sample.rb ADDED
@@ -0,0 +1,82 @@
1
+ #
2
+ # 22 Jul 2012
3
+ #
4
+
5
+ $LOAD_PATH << "."
6
+
7
+ require "log4ruby"
8
+ require "log4ruby/appenders/console_appender"
9
+ require "log4ruby/appenders/file_appender"
10
+ require "log4ruby/formatters/pattern_formatter"
11
+
12
+ # The pattern formatter, with a custom parameter formatter for the timestamp and the logger.
13
+ formatter = Log4Ruby::PatternFormatter.new("[%s] %7s - %s : %s (%s)\n", [:timestamp, :level, :logger, :message, :extra])
14
+ formatter.add_parameter_formatter(:logger, Log4Ruby::ParameterFormatters.logger_formatter(1))
15
+ formatter.add_parameter_formatter(:timestamp, Log4Ruby::ParameterFormatters.timestamp_formatter("%Y-%m-%d %H:%M:%S.%L"))
16
+ # Console appender for printing to stdout.
17
+ console_appender = Log4Ruby::ConsoleAppender.new(Log4Ruby::Level::ALL, :target => :stdout)
18
+ # Rolling file appender
19
+ file_appender = Log4Ruby::FileAppender.new(Log4Ruby::Level::ALL, :roll_type => :dont_roll,
20
+ :directory => "../logs", :prefix => "TestLogger")
21
+ size_appender = Log4Ruby::FileAppender.new(Log4Ruby::Level::ALL, :formatter => formatter, :roll_type => :roll_using_size,
22
+ :directory => "../logs", :prefix => "TestLoggerSize", :max_size => 1024)
23
+ date_appender = Log4Ruby::FileAppender.new(Log4Ruby::Level::ALL, :formatter => formatter, :roll_type => :roll_using_date,
24
+ :directory => "../logs", :prefix => "TestLoggerDate", :frequency => :hourly)
25
+
26
+ # XML formatter.
27
+ indent = " "
28
+ log_start_element = "#{indent}<log>"
29
+ timestamp_element = "#{indent * 2}<timestamp>%s</timestamp>"
30
+ level_element = "#{indent * 2}<level>%s</level>"
31
+ logger_element = "#{indent * 2}<logger>%s</logger>"
32
+ message_element = "#{indent * 2}<message>%s</message>"
33
+ log_end_element = "#{indent}</log>"
34
+ format_string = [log_start_element, timestamp_element, level_element, logger_element, message_element, log_end_element].join("\n")
35
+ xml_formatter = Log4Ruby::PatternFormatter.new("#{format_string}\n", [:timestamp, :level, :logger, :message])
36
+ # XML appender (with custom header and footer methods)
37
+ xml_appender = Log4Ruby::FileAppender.new(Log4Ruby::Level::ALL, :formatter => xml_formatter, :roll_type => :dont_roll,
38
+ :directory => "../logs", :prefix => "TestLogger", :suffix => "xml")
39
+
40
+ # Custom header / footer methods.
41
+ xml_appender.header { |stream| stream.write("<logs>\n") }
42
+ xml_appender.footer { |stream| stream.write("</logs>\n") }
43
+
44
+ # Register a custom level FINER, that is between TRACE and FINE
45
+ Log4Ruby::Level.register("FINER", 150.0)
46
+
47
+ # The loggers.
48
+ # TestLogger is a child of the Log4Ruby logger. So even though the ConsoleAppender is added to the Log4Ruby logger,
49
+ # logs created using TestLogger are printed on the console (upto the level DEBUG). This is because TestLogger will
50
+ # forward logs to its parent's appenders. This behaviour can be turned off using the use_parent_appenders flag.
51
+ log4ruby_logger = Log4Ruby.get_logger("Log4Ruby")
52
+ log4ruby_logger.set_level(Log4Ruby::Level::DEBUG)
53
+ log4ruby_logger.add_appender(console_appender)
54
+ test_logger = Log4Ruby.get_logger("Log4Ruby::TestLogger")
55
+ test_logger.add_appender(xml_appender)
56
+ test_logger.add_appender(file_appender)
57
+ test_logger.add_appender(size_appender)
58
+ test_logger.add_appender(date_appender)
59
+
60
+ # Additionally, the test logger will inherit the effective level of its parent, unless explicitly overridden.
61
+ puts "Inherited level is #{test_logger.effective_level}"
62
+ puts "Logger will print TRACE? : #{test_logger.trace?}"
63
+ puts "Logger will print FINER? : #{test_logger.finer?}"
64
+ puts "Logger will print FINE? : #{test_logger.fine?}"
65
+ test_logger.set_level(Log4Ruby::Level::FINER)
66
+ puts "Updated level to #{test_logger.effective_level}."
67
+ puts "Logger will print TRACE? : #{test_logger.trace?}"
68
+ puts "Logger will print FINER? : #{test_logger.finer?}"
69
+ puts "Logger will print FINE? : #{test_logger.fine?}"
70
+
71
+ # Logs are created by directly invoking the required methods (these are dynamically created on the Logger class).
72
+ # The log methods can also take an optional hash of attributes. The formatter can then be configured to print those
73
+ # values.
74
+ test_logger.trace("Test!", :extra => "Trace")
75
+ test_logger.finer("Test!", :extra => "Finer")
76
+ test_logger.fine("Test!", :extra => "Fine")
77
+ test_logger.debug("Test!", :extra => "Debug")
78
+ test_logger.conf("Test!", :extra => "Conf")
79
+ test_logger.info("Test!")
80
+ test_logger.warn("Test!")
81
+ test_logger.error("Test!")
82
+ test_logger.fatal("Test!")
metadata CHANGED
@@ -1,48 +1,34 @@
1
- --- !ruby/object:Gem::Specification
1
+ --- !ruby/object:Gem::Specification
2
2
  name: log4ruby
3
- version: !ruby/object:Gem::Version
4
- hash: 25
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.4
5
5
  prerelease:
6
- segments:
7
- - 0
8
- - 0
9
- - 3
10
- version: 0.0.3
11
6
  platform: ruby
12
- authors:
7
+ authors:
13
8
  - Suraj Vijayakumar
14
9
  autorequire:
15
10
  bindir: bin
16
11
  cert_chain: []
17
-
18
- date: 2012-07-24 00:00:00 Z
19
- dependencies:
20
- - !ruby/object:Gem::Dependency
12
+ date: 2012-07-26 00:00:00.000000000Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
21
15
  name: options-arg
22
- prerelease: false
23
- requirement: &id001 !ruby/object:Gem::Requirement
16
+ requirement: &7797456 !ruby/object:Gem::Requirement
24
17
  none: false
25
- requirements:
26
- - - ">="
27
- - !ruby/object:Gem::Version
28
- hash: 29
29
- segments:
30
- - 0
31
- - 0
32
- - 1
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
33
21
  version: 0.0.1
34
22
  type: :runtime
35
- version_requirements: *id001
23
+ prerelease: false
24
+ version_requirements: *7797456
36
25
  description: A logging system for Ruby applications inspired by Java's logging API.
37
- email:
26
+ email:
38
27
  - vijayakumar.suraj@gmail.com
39
28
  executables: []
40
-
41
29
  extensions: []
42
-
43
30
  extra_rdoc_files: []
44
-
45
- files:
31
+ files:
46
32
  - lib/log4ruby/appender.rb
47
33
  - lib/log4ruby/appenders/console_appender.rb
48
34
  - lib/log4ruby/appenders/file_appender.rb
@@ -50,47 +36,36 @@ files:
50
36
  - lib/log4ruby/appenders/stream_appender.rb
51
37
  - lib/log4ruby/exceptions.rb
52
38
  - lib/log4ruby/formatter.rb
39
+ - lib/log4ruby/formatters/default_formatter.rb
53
40
  - lib/log4ruby/formatters/pattern_formatter.rb
54
41
  - lib/log4ruby/level.rb
55
42
  - lib/log4ruby/log.rb
56
43
  - lib/log4ruby/logger.rb
57
44
  - lib/log4ruby/version.rb
58
45
  - lib/log4ruby.rb
59
- - lib/tests.rb
46
+ - lib/sample.rb
60
47
  homepage:
61
48
  licenses: []
62
-
63
49
  post_install_message:
64
50
  rdoc_options: []
65
-
66
- require_paths:
51
+ require_paths:
67
52
  - lib
68
- required_ruby_version: !ruby/object:Gem::Requirement
53
+ required_ruby_version: !ruby/object:Gem::Requirement
69
54
  none: false
70
- requirements:
71
- - - ">="
72
- - !ruby/object:Gem::Version
73
- hash: 51
74
- segments:
75
- - 1
76
- - 9
77
- - 0
55
+ requirements:
56
+ - - ! '>='
57
+ - !ruby/object:Gem::Version
78
58
  version: 1.9.0
79
- required_rubygems_version: !ruby/object:Gem::Requirement
59
+ required_rubygems_version: !ruby/object:Gem::Requirement
80
60
  none: false
81
- requirements:
82
- - - ">="
83
- - !ruby/object:Gem::Version
84
- hash: 3
85
- segments:
86
- - 0
87
- version: "0"
61
+ requirements:
62
+ - - ! '>='
63
+ - !ruby/object:Gem::Version
64
+ version: '0'
88
65
  requirements: []
89
-
90
66
  rubyforge_project:
91
- rubygems_version: 1.8.24
67
+ rubygems_version: 1.7.2
92
68
  signing_key:
93
69
  specification_version: 3
94
70
  summary: A simple and customizable logging system inspired by Java logging API.
95
71
  test_files: []
96
-
data/lib/tests.rb DELETED
@@ -1,49 +0,0 @@
1
- #
2
- # 22 Jul 2012
3
- #
4
-
5
- $LOAD_PATH << "."
6
-
7
- require "log4ruby"
8
- require "log4ruby/appenders/console_appender"
9
- require "log4ruby/appenders/file_appender"
10
- require "log4ruby/formatters/pattern_formatter"
11
-
12
- # The pattern formatter, with a custom parameter formatter for the timestamp.
13
- formatter = Log4Ruby::PatternFormatter.new("[%s] %7s - %s : %s\n", [:timestamp, :level, :logger, :message])
14
- formatter.add_parameter_formatter(:logger, Log4Ruby::ParameterFormatters.logger_formatter(1))
15
- formatter.add_parameter_formatter(:timestamp, Log4Ruby::ParameterFormatters.timestamp_formatter("%Y-%m-%d %H:%M:%S.%L"))
16
- # Stream appender for printing to stdout.
17
- console_appender = Log4Ruby::ConsoleAppender.new(Log4Ruby::Level::ALL, formatter, :stdout)
18
- # Rolling file appender
19
- file_appender = Log4Ruby::FileAppender.new(Log4Ruby::Level::ALL, formatter, :roll_type => :dont_roll,
20
- :directory => "../logs", :prefix => "TestLogger")
21
- size_appender = Log4Ruby::FileAppender.new(Log4Ruby::Level::ALL, formatter, :roll_type => :roll_using_size,
22
- :directory => "../logs", :prefix => "TestLoggerSize", :max_size => 1024)
23
- date_appender = Log4Ruby::FileAppender.new(Log4Ruby::Level::ALL, formatter, :roll_type => :roll_using_date,
24
- :directory => "../logs", :prefix => "TestLoggerDate", :frequency => :hourly)
25
-
26
- # Register a custom level FINER, that is between TRACE and FINE
27
- Log4Ruby::Level.register("FINER", 150.0)
28
-
29
- # The logger.
30
- logger = Log4Ruby.get_logger("Log4Ruby::TestLogger")
31
- logger.set_level(Log4Ruby::Level::FINER)
32
- logger.add_appender(console_appender)
33
- logger.add_appender(file_appender)
34
- logger.add_appender(size_appender)
35
- logger.add_appender(date_appender)
36
-
37
- puts "Logger will print TRACE? : #{logger.trace?}"
38
- puts "Logger will print FINER? : #{logger.finer?}"
39
- puts "Logger will print FINE? : #{logger.fine?}"
40
-
41
- logger.trace("Test!")
42
- logger.finer("Test!")
43
- logger.fine("Test!")
44
- logger.debug("Test!")
45
- logger.conf("Test!")
46
- logger.info("Test!")
47
- logger.warn("Test!")
48
- logger.error("Test!")
49
- logger.fatal("Test!")