yank out Log::Any adapter - it was only an experiment
[scpubgit/Object-Remote.git] / lib / Object / Remote / Logging.pm
5e2b2229 1package Object::Remote::Logging;
4e446335 3use Moo;
4use Scalar::Util qw(blessed);
5use Object::Remote::Logging::Logger;
f4a85080 6use Exporter::Declare;
663fb34f 7use Carp qw(carp croak);
5e2b2229 8
4e446335 9extends 'Log::Contextual';
5e2b2229 10
663fb34f 11exports(qw( ____ router arg_levels ));
12#exception log - log a message then die with that message
13export_tag elog => ('____');
14#fatal log - log a message then call exit(1)
15export_tag flog => ('____');
f4a85080 16
4e446335 17sub router {
c0b2df05 18 our $Router_Instance ||= do {
19 require Object::Remote::Logging::Router;
20 Object::Remote::Logging::Router->new;
21 }
4e446335 22}
5e2b2229 23
9de32e1d 24#log level descriptions
25#info - standard log level - normal program output for the end user
26#warn - output for program that is executing quietly
27#error - output for program that is running more quietly
28#fatal - it is not possible to continue execution; this level is as quiet as is possible
29#verbose - output for program executing verbosely (-v)
30#debug - output for program running more verbosely (-v -v)
31#trace - output for program running extremely verbosely (-v -v -v)
4e446335 32sub arg_levels {
9de32e1d 33 #the order of the log levels is significant with the
34 #most verbose level being first in the list and the
35 #most quiet as the last item
36 return [qw( trace debug verbose info warn error fatal )];
4a9fa1a5 37}
5e2b2229 38
663fb34f 39sub before_import {
40 my ($class, $importer, $spec) = @_;
41 my $router = $class->router;
43 $class->SUPER::before_import($importer, $spec);
45 my @levels = @{$class->arg_levels($spec->config->{levels})};
46 for my $level (@levels) {
47 if ($spec->config->{elog}) {
48 $spec->add_export("&Elog_$level", sub (&) {
49 my ($code, @args) = @_;
50 $router->handle_log_request({
51 controller => $class,
52 package => scalar(caller),
53 caller_level => 1,
54 level => $level,
55 }, $code);
56 #TODO this should get fed into a logger so it can be formatted
57 croak $code->();
58 });
59 }
60 if ($spec->config->{flog}) {
61 #TODO that prototype isn't right
62 $spec->add_export("&Flog_$level", sub (&@) {
63 my ($code, $exit_value) = @_;
64 $exit_value = 1 unless defined $exit_value;
455d031c 65 #don't let it going wrong stop us from calling exit()
66 eval { $router->handle_log_request({
663fb34f 67 controller => $class,
68 package => scalar(caller),
69 caller_level => 1,
70 level => $level,
455d031c 71 }, $code) };
5cd5276e 72 warn "could not deliver log event during Flog_$level: $@" if $@;
d672a9bf 73 eval { carp $code->() };
5cd5276e 74 warn "could not emit warning during Flog_$level: $@" if $@;
663fb34f 75 exit($exit_value);
76 });
77 }
78 }
ae198201 81sub _parse_selections {
82 my ($selections_string) = @_;
83 my %log_ok;
85 #example string:
86 #" * -Object::Remote::Logging Foo::Bar::Baz "
87 foreach(split(/\s+/, $selections_string)) {
88 next if $_ eq '';
89 if ($_ eq '*') {
90 $log_ok{$_} = 1;
91 } elsif (s/^-//) {
92 $log_ok{$_} = 0;
93 } else {
94 $log_ok{$_} = 1;
95 }
96 }
98 return %log_ok;
4e446335 101#this is invoked on all nodes
4a9fa1a5 102sub init_logging {
c0b2df05 103 my $level = $ENV{OBJECT_REMOTE_LOG_LEVEL};
0fe333eb 104 my $format = $ENV{OBJECT_REMOTE_LOG_FORMAT};
eb49c7df 105 my $selections = $ENV{OBJECT_REMOTE_LOG_SELECTIONS};
106 my %controller_should_log;
5cd5276e 107
c0b2df05 108 return unless defined $level;
0fe333eb 109 $format = "[%l %r] %s" unless defined $format;
eb49c7df 110 $selections = __PACKAGE__ unless defined $selections;
ae198201 111 %controller_should_log = _parse_selections($selections);
eb49c7df 112
c0b2df05 113 my $logger = Object::Remote::Logging::Logger->new(
0fe333eb 114 min_level => lc($level), format => $format,
c0b2df05 115 level_names => Object::Remote::Logging::arg_levels(),
116 );
c0b2df05 118 router()->connect(sub {
eb49c7df 119 my $controller = $_[1]->{controller};
ae198201 120 my $will_log = $controller_should_log{$controller};
122 $will_log = $controller_should_log{'*'} unless defined $will_log;
124 return unless $will_log;
c0b2df05 125 #skip things from remote hosts because they log to STDERR
126 #when OBJECT_REMOTE_LOG_LEVEL is in effect
127 return if $_[1]->{remote}->{connection_id};
128 $logger
129 });
4a9fa1a5 130}
4e446335 132#this is invoked by the controlling node
133#on the remote nodes
4a9fa1a5 134sub init_logging_forwarding {
4e446335 135 my ($self, %controller_info) = @_;
137 router()->_remote_metadata({ connection_id => $controller_info{connection_id} });
f048e6df 138 #TODO having an instance of an object in the remote interpreter causes it to hang
139 #on exit intermitently or leave a zombie laying around frequently - not a bug limited
140 #to log forwarding
466ee2c4 141 router()->_forward_destination($controller_info{router}) if $ENV{OBJECT_REMOTE_LOG_FORWARDING};
4a9fa1a5 142}
5e2b2229 143
455d031c 145
d672a9bf 146__END__
148=head1 NAME
150Object::Remote::Logging - Logging subsystem for Object::Remote
152=head1 SYNOPSIS
154 use Object::Remote::Logging qw( :log :dlog :elog :flog arg_levels router );
156 @levels = qw( trace debug verbose info warn error fatal );
157 @levels = arg_levels(); #same result
159 $ENV{OBJECT_REMOTE_LOG_LEVEL} = 'trace'; #or other level name
160 $ENV{OBJECT_REMOTE_LOG_FORMAT} = '%l %t: %p::%m %s'; #and more
d672a9bf 161 $ENV{OBJECT_REMOTE_LOG_SELECTIONS} = 'Object::Remote::Logging Some::Other::Subclass';
ae198201 162 $ENV{OBJECT_REMOTE_LOG_SELECTIONS} = '* -Object::Remote::Logging';
455d031c 163 $ENV{OBJECT_REMOTE_LOG_FORWARDING} = 0 || 1; #default 0
d672a9bf 164
165 log_info { 'Trace log event' };
166 Dlog_verbose { "Debug event with Data::Dumper::Concise: $_" } { foo => 'bar' };
167 Elog_error { 'Error event that calls die() with this string' };
168 Flog_fatal { 'Fatal event calls warn() then exit()' } 1;
172This is the logging framework for Object::Remote implemented as a subclass of
173L<Log::Contextual> with a slightly incompatible API. This system allows
174developers using Object::Remote and end users of that software to control
175Object::Remote logging so operation can be tracked if needed. This is also
176the API used to generate log messages inside the Object::Remote source code.
178The rest of the logging system comes from L<Object::Remote::Logging::Logger>
179which implements log rendering and output and L<Object::Remote::Logging::Router>
180which delivers log events to the loggers.
455d031c 182=head1 USAGE
184Object::Remote logging is not enabled by default. If you need to immediately start
185debugging set the OBJECT_REMOTE_LOG_LEVEL environment variable to either 'trace'
186or 'debug'. This will enable logging to STDERR on the local and all remote Perl
187interpreters. By default STDERR for all remote interpreters is passed through
188unmodified so this is sufficient to receive logs generated anywhere Object::Remote
189is running.
191Every time the local interpreter creates a new Object::Remote::Connection the connection
192is given an id that is unique to that connection on the local interpreter. The connection
193id and other metadata is available in the log output via a log format string that can
194be set via the OBJECT_REMOTE_LOG_FORMAT environment variable. The format string and
195available metadata is documented in L<Object::Remote::Logging::Logger>. Setting this
196environment variable on the local interpreter will cause it to be propagated to the
197remote interpreter so all logs will be formated the same way.
199This class is designed so any module can create their own logging sub-class using it.
f21127fd 200With out any additional configuration the consumers of this logging class will
201automatically be enabled via OBJECT_REMOTE_LOG_LEVEL and formated with
202OBJECT_REMOTE_LOG_FORMAT but those additional log messages are not sent to STDERR.
203By setting the OBJECT_REMOTE_LOG_SELECTIONS environment variable to a list of
204class names seperated by spaces then logs generated by packages that use those classes
ae198201 205will be sent to STDERR. If the asterisk character (*) is used in the place of a class
206name then all class names will be selected by default instead of ignored. An individual
207class name can be turned off by prefixing the name with a hypen character (-). This is
208also a configuration item that is forwarded to the remote interpreters so all logging
209is consistent.
455d031c 210
211Regardless of OBJECT_REMOTE_LOG_LEVEL the logging system is still active and loggers
212can access the stream of log messages to format and output them. Internally
213OBJECT_REMOTE_LOG_LEVEL causes an L<Object::Remote::Logging::Logger> to be built
214and connected to the L<Object::Remote::Logging::Router> instance. It is also possible
215to manually build a logger instance and connect it to the router. See the documentation
f21127fd 216for the logger and router classes.
455d031c 217
218The logging system also supports a method of forwarding log messages from remote
219interpreters to the local interpreter. Forwarded log messages are generated in the
220remote interpreter and the logger for the message is invoked in the local interpreter.
221Sub-classes of Object::Remote::Logging will have log messages forwarded automatically.
222Loggers receive forwarded log messages exactly the same way as non-forwarded messages
223except a forwarded message includes extra metadata about the remote interpreter. Log
224forwarding is not currently enabled by default; to enable it set the
225OBJECT_REMOTE_LOG_FORWARDING environment variable to 1. See L<Object::Remote::Logging::Router>.
229=over 4
231=item arg_levels
233Returns an array reference that contains the ordered list of level names
234with the lowest log level first and the highest log level last.
236=item router
238Returns the instance of L<Object::Remote::Logging::Router> that is in use. The router
239instance is used in combination with L<Object::Remote::Logging::Logger> objects to
240select then render and output log messages.
242=item log_<level> and Dlog_<level>
244These methods come direct from L<Log::Contextual>; see that documentation for a
245complete reference. For each of the log level names there are subroutines with the log_
246and Dlog_ prefix that will generate the log message. The first argument is a code block
247that returns the log message contents and the optional further arguments are both passed
248to the block as the argument list and returned from the log method as a list.
250 log_trace { "A fine log message $_[0] " } 'if I do say so myself';
455d031c 251 %hash = Dlog_trace { "Very handy: $_" } ( foo => 'bar' );
d672a9bf 252
253=item logS_<level> and DlogS_<level>
255Works just like log_ and Dlog_ except returns only the first argument as a scalar value.
257 my $beverage = log_info { "Customer ordered $_[0]" } 'Coffee';
259=item Elog_<level>
261Log an event and then generate an exception by calling die() with the log message.
263 Elog_error { "Could not open file: $!" };
265=item Flog_<level>
267Log the event, generate a warning with the log message, then call exit(). The exit
268value will default to 1 or can be specified as an argument.
270 Flog_fatal { 'Could not lock resource' } 3;
274=head1 LEVEL NAMES
293fb1ee 276Object::Remote uses an ordered list of log level names with the lowest level
277first and the highest level last. The list of level names can be accessed via
d672a9bf 278the arg_levels method which is exportable to the consumer of this class. The log
279level names are:
281=over 4
283=item trace
285As much information about operation as possible including multiple line dumps of
286large content. Tripple verbose operation (-v -v -v).
288=item debug
290Messages about operations that could hang as well as internal state changes,
291results from method invocations, and information useful when looking for faults.
292Double verbose operation (-v -v).
294=item verbose
296Additional optional messages to the user that can be enabled at their will. Single
297verbose operation (-v).
299=item info
301Messages from normal operation that are intended to be displayed to the end
302user if quiet operation is not indicated and more verbose operation is not
303in effect.
305=item warn
307Something wasn't supposed to happen but did. Operation was not impacted but
308otherwise the event is noteworthy. Single quiet operation (-q).
310=item error
312Something went wrong. Operation of the system may continue but some operation
313has most definitely failed. Double quiet operation (-q -q).
315=item fatal
317Something went wrong and recovery is not possible. The system should stop operating
318as soon as possible. Tripple quiet operation (-q -q -q).