9bdc530705ab3e505314b69382c8e11f34df9472
[packages/precise/mcollective.git] / lib / mcollective / logger / base.rb
1 module MCollective
2   module Logger
3     # A base class for logging providers.
4     #
5     # Logging providers should provide the following:
6     #
7     #    * start - all you need to do to setup your logging
8     #    * set_logging_level - set your logging to :info, :warn, etc
9     #    * valid_levels - a hash of maps from :info to your internal level name
10     #    * log - what needs to be done to log a specific message
11     class Base
12       attr_reader :active_level
13
14       def initialize
15         @known_levels = [:debug, :info, :warn, :error, :fatal]
16
17         # Sanity check the class that impliments the logging
18         @known_levels.each do |lvl|
19           raise "Logger class did not specify a map for #{lvl}" unless valid_levels.include?(lvl)
20         end
21       end
22
23       def should_log?(level)
24         @known_levels.index(level) >= @known_levels.index(@active_level)
25       end
26
27       # Figures out the next level and sets it
28       def cycle_level
29         lvl = get_next_level
30         set_level(lvl)
31
32         log(lvl, "", "Logging level is now #{lvl.to_s.upcase}")
33       end
34
35       # Sets a new level and record it in @active_level
36       def set_level(level)
37         set_logging_level(level)
38         @active_level = level.to_sym
39       end
40
41       private
42       def map_level(level)
43         raise "Logger class do not know how to handle #{level} messages" unless valid_levels.include?(level.to_sym)
44
45         valid_levels[level.to_sym]
46       end
47
48       # Gets the next level in the list, cycles down to the firt once it reaches the end
49       def get_next_level
50         # if all else fails, always go to debug mode
51         nextlvl = :debug
52
53         if @known_levels.index(@active_level) == (@known_levels.size - 1)
54           nextlvl = @known_levels.first
55         else
56           idx = @known_levels.index(@active_level) + 1
57           nextlvl = @known_levels[idx]
58         end
59
60         nextlvl
61       end
62
63       # Abstract methods to ensure the logging implimentations supply what they should
64       def valid_levels
65         raise "The logging class did not supply a valid_levels method"
66       end
67
68       def log(level, from, msg)
69         raise "The logging class did not supply a log method"
70       end
71
72       def start
73         raise "The logging class did not supply a start method"
74       end
75     end
76   end
77 end