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