remove comment for bug that was fixed
[scpubgit/Object-Remote.git] / lib / Object / Remote / Logging.pm
1 package Object::Remote::Logging;
2
3 use Moo;
4 use Scalar::Util qw(blessed);
5 use Object::Remote::Logging::Logger;
6 use Exporter::Declare;
7 use Carp qw(carp croak);
8
9 extends 'Log::Contextual';
10
11 exports(qw( ____ router arg_levels ));
12
13 sub router {
14   our $Router_Instance ||= do {
15     require Object::Remote::Logging::Router;
16     Object::Remote::Logging::Router->new;
17   }
18 }
19
20 #log level descriptions
21 #info - standard log level - normal program output for the end user
22 #warn - output for program that is executing quietly
23 #error - output for program that is running more quietly
24 #fatal - it is not possible to continue execution; this level is as quiet as is possible
25 #verbose - output for program executing verbosely (-v)
26 #debug - output for program running more verbosely (-v -v)
27 #trace - output for program running extremely verbosely (-v -v -v)
28 sub arg_levels {
29   #the order of the log levels is significant with the
30   #most verbose level being first in the list and the
31   #most quiet as the last item
32   return [qw( trace debug verbose info warn error fatal )];
33 }
34
35 sub before_import {
36    my ($class, $importer, $spec) = @_;
37    my $router = $class->router;
38    our $DID_INIT;
39
40    unless($DID_INIT) {
41      $DID_INIT = 1;
42      init_logging();
43    }
44       
45    $class->SUPER::before_import($importer, $spec);
46 }
47
48 sub _parse_selections {
49     my ($selections_string) = @_;
50     my %log_ok;
51     
52     #example string:
53     #"  * -Object::Remote::Logging    Foo::Bar::Baz   "
54     foreach(split(/\s+/, $selections_string)) {
55         next if $_ eq '';
56         if ($_ eq '*') {
57             $log_ok{$_} = 1;
58         } elsif (s/^-//) {
59             $log_ok{$_} = 0;
60         } else {
61             $log_ok{$_} = 1;
62         }
63     }
64     
65     return %log_ok;
66 }
67
68 #this is invoked on all nodes
69 sub init_logging {
70   my $level = $ENV{OBJECT_REMOTE_LOG_LEVEL};
71   my $format = $ENV{OBJECT_REMOTE_LOG_FORMAT};
72   my $selections = $ENV{OBJECT_REMOTE_LOG_SELECTIONS};
73   my %controller_should_log;
74   
75   unless (defined $ENV{OBJECT_REMOTE_LOG_FORWARDING} && $ENV{OBJECT_REMOTE_LOG_FORWARDING} ne '') {
76     $ENV{OBJECT_REMOTE_LOG_FORWARDING} = 1;
77   }
78
79   return unless defined $level && $level ne '';
80   $format = "[%l %r] %s" unless defined $format;
81   $selections = __PACKAGE__ unless defined $selections;
82   %controller_should_log = _parse_selections($selections);
83
84   {
85     no warnings 'once';
86     if (defined $Object::Remote::FatNode::REMOTE_NODE) {
87       #the connection id for the remote node comes in later
88       #as the controlling node inits remote logging
89       router()->_remote_metadata({ connection_id =>  undef });
90     } 
91   }
92
93   my $logger = Object::Remote::Logging::Logger->new(
94     min_level => lc($level), format => $format,
95     level_names => Object::Remote::Logging::arg_levels(),
96   );
97
98   router()->connect(sub { 
99     my $controller = $_[1]->{controller};
100     my $will_log = $controller_should_log{$controller};
101     
102     $will_log = $controller_should_log{'*'} unless defined $will_log;
103     
104     return unless $will_log;
105     #skip things from remote hosts because they log to STDERR
106     #when OBJECT_REMOTE_LOG_LEVEL is in effect
107     return if $_[1]->{remote}->{connection_id};
108     $logger
109   });
110 }
111
112 #this is invoked by the controlling node
113 #on the remote nodes
114 sub init_remote_logging {
115   my ($self, %controller_info) = @_;
116   
117   router()->_remote_metadata(\%controller_info);
118   router()->_forward_destination($controller_info{router}) if $ENV{OBJECT_REMOTE_LOG_FORWARDING};
119 }
120
121 1;
122
123 __END__
124
125 =head1 NAME
126
127 Object::Remote::Logging - Logging subsystem for Object::Remote
128
129 =head1 SYNOPSIS
130
131   use Object::Remote::Logging qw( :log :dlog arg_levels router );
132   
133   @levels = qw( trace debug verbose info warn error fatal );
134   @levels = arg_levels(); #same result
135   
136   $ENV{OBJECT_REMOTE_LOG_LEVEL} = 'trace'; #or other level name
137   $ENV{OBJECT_REMOTE_LOG_FORMAT} = '%l %t: %p::%m %s'; #and more
138   $ENV{OBJECT_REMOTE_LOG_SELECTIONS} = 'Object::Remote::Logging Some::Other::Subclass';
139   $ENV{OBJECT_REMOTE_LOG_SELECTIONS} = '* -Object::Remote::Logging';
140   $ENV{OBJECT_REMOTE_LOG_FORWARDING} = 0; #default 1
141   
142   log_info { 'Trace log event' };
143   Dlog_verbose { "Debug event with Data::Dumper::Concise: $_" } { foo => 'bar' };
144
145 =head1 DESCRIPTION
146
147 This is the logging framework for Object::Remote implemented as a subclass of
148 L<Log::Contextual> with a slightly incompatible API. This system allows 
149 developers using Object::Remote and end users of that software to control
150 Object::Remote logging so operation can be tracked if needed. This is also
151 the API used to generate log messages inside the Object::Remote source code.
152
153 The rest of the logging system comes from L<Object::Remote::Logging::Logger>
154 which implements log rendering and output and L<Object::Remote::Logging::Router>
155 which delivers log events to the loggers.
156
157 =head1 USAGE
158
159 Object::Remote logging is not enabled by default. If you need to immediately start
160 debugging set the OBJECT_REMOTE_LOG_LEVEL environment variable to either 'trace'
161 or 'debug'. This will enable logging to STDERR on the local and all remote Perl 
162 interpreters. By default STDERR for all remote interpreters is passed through
163 unmodified so this is sufficient to receive logs generated anywhere Object::Remote
164 is running.
165
166 Every time the local interpreter creates a new Object::Remote::Connection the connection
167 is given an id that is unique to that connection on the local interpreter. The connection
168 id and other metadata is available in the log output via a log format string that can
169 be set via the OBJECT_REMOTE_LOG_FORMAT environment variable. The format string and
170 available metadata is documented in L<Object::Remote::Logging::Logger>. Setting this
171 environment variable on the local interpreter will cause it to be propagated to the 
172 remote interpreter so all logs will be formated the same way.
173
174 This class is designed so any module can create their own logging sub-class using it.
175 With out any additional configuration the consumers of this logging class will
176 automatically be enabled via OBJECT_REMOTE_LOG_LEVEL and formated with 
177 OBJECT_REMOTE_LOG_FORMAT but those additional log messages are not sent to STDERR. 
178 By setting the  OBJECT_REMOTE_LOG_SELECTIONS environment variable to a list of
179 class names seperated by spaces then logs generated by packages that use those classes
180 will be sent to STDERR. If the asterisk character (*) is used in the place of a class
181 name then all class names will be selected by default instead of ignored. An individual
182 class name can be turned off by prefixing the name with a hypen character (-). This is
183 also a configuration item that is forwarded to the remote interpreters so all logging
184 is consistent.
185
186 Regardless of OBJECT_REMOTE_LOG_LEVEL the logging system is still active and loggers
187 can access the stream of log messages to format and output them. Internally
188 OBJECT_REMOTE_LOG_LEVEL causes an L<Object::Remote::Logging::Logger> to be built
189 and connected to the L<Object::Remote::Logging::Router> instance. It is also possible
190 to manually build a logger instance and connect it to the router. See the documentation
191 for the logger and router classes.
192
193 The logging system also supports a method of forwarding log messages from remote
194 interpreters to the local interpreter. Forwarded log messages are generated in the
195 remote interpreter and the logger for the message is invoked in the local interpreter.
196 Sub-classes of Object::Remote::Logging will have log messages forwarded automatically.
197 Loggers receive forwarded log messages exactly the same way as non-forwarded messages
198 except a forwarded message includes extra metadata about the remote interpreter. Log
199 forwarding is enabled by default but comes with a performance hit; to disable it set the 
200 OBJECT_REMOTE_LOG_FORWARDING environment variable to 0. See L<Object::Remote::Logging::Router>.
201
202 =head1 EXPORTABLE SUBROUTINES
203
204 =over 4
205
206 =item arg_levels
207
208 Returns an array reference that contains the ordered list of level names
209 with the lowest log level first and the highest log level last.
210
211 =item router
212
213 Returns the instance of L<Object::Remote::Logging::Router> that is in use. The router
214 instance is used in combination with L<Object::Remote::Logging::Logger> objects to
215 select then render and output log messages.
216
217 =item log_<level> and Dlog_<level>
218
219 These methods come direct from L<Log::Contextual>; see that documentation for a 
220 complete reference. For each of the log level names there are subroutines with the log_
221 and Dlog_ prefix that will generate the log message. The first argument is a code block
222 that returns the log message contents and the optional further arguments are both passed
223 to the block as the argument list and returned from the log method as a list.
224
225   log_trace { "A fine log message $_[0] " } 'if I do say so myself';
226   %hash = Dlog_trace { "Very handy: $_" } ( foo => 'bar' );
227
228 =item logS_<level> and DlogS_<level>
229
230 Works just like log_ and Dlog_ except returns only the first argument as a scalar value.
231
232   my $beverage = logS_info { "Customer ordered $_[0]" } 'Coffee';
233
234 =back
235
236 =head1 LEVEL NAMES
237
238 Object::Remote uses an ordered list of log level names with the lowest level
239 first and the highest level last. The list of level names can be accessed via
240 the arg_levels method which is exportable to the consumer of this class. The log
241 level names are:
242
243 =over 4
244
245 =item trace
246
247 As much information about operation as possible including multiple line dumps of
248 large content. Tripple verbose operation (-v -v -v).
249
250 =item debug
251
252 Messages about operations that could hang as well as internal state changes, 
253 results from method invocations, and information useful when looking for faults.
254 Double verbose operation (-v -v).
255
256 =item verbose
257
258 Additional optional messages to the user that can be enabled at their will. Single
259 verbose operation (-v).
260
261 =item info
262
263 Messages from normal operation that are intended to be displayed to the end
264 user if quiet operation is not indicated and more verbose operation is not
265 in effect.
266
267 =item warn
268
269 Something wasn't supposed to happen but did. Operation was not impacted but
270 otherwise the event is noteworthy. Single quiet operation (-q).
271
272 =item error
273
274 Something went wrong. Operation of the system may continue but some operation
275 has most definitely failed. Double quiet operation (-q -q).
276
277 =item fatal
278
279 Something went wrong and recovery is not possible. The system should stop operating
280 as soon as possible. Tripple quiet operation (-q -q -q).
281
282 =back