ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent/Log.pm
Revision: 1.11
Committed: Sat Aug 20 01:03:09 2011 UTC (12 years, 10 months ago) by root
Branch: MAIN
Changes since 1.10: +132 -56 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 =head1 NAME
2
3 AnyEvent::Log - simple logging "framework"
4
5 =head1 SYNOPSIS
6
7 # simple use
8 use AnyEvent;
9
10 AE::log debug => "hit my knee";
11 AE::log warn => "it's a bit too hot";
12 AE::log error => "the flag was false!";
13 AE::log fatal => "the bit toggled! run!";
14
15 # "complex" use
16 use AnyEvent::Log;
17
18 my $tracer = AnyEvent::Log::logger trace => \$my $trace;
19
20 $tracer->("i am here") if $trace;
21 $tracer->(sub { "lots of data: " . Dumper $self }) if $trace;
22
23 # configuration
24
25 # set logging for this package to maximum
26 AnyEvent::Log::ctx->level ("all");
27
28 # set logging globally to anything below debug
29 (AnyEvent::Log::ctx "")->level ("notice");
30
31 # see also EXAMPLES, below
32
33 # disable logging for package "AnyEvent" and all packages below it
34 AnyEvent->AnyEvent::Log::ctx->level (0);
35
36 # log everything below debug to a file, for the whole program
37 my $ctx = AnyEvent::Log::ctx;
38 $ctx->log_cb (sub { print FILE shift; 0 });
39 (AnyEvent::Log::ctx "")->add ($ctx);
40
41 =head1 DESCRIPTION
42
43 This module implements a relatively simple "logging framework". It doesn't
44 attempt to be "the" logging solution or even "a" logging solution for
45 AnyEvent - AnyEvent simply creates logging messages internally, and this
46 module more or less exposes the mechanism, with some extra spiff to allow
47 using it from other modules as well.
48
49 Remember that the default verbosity level is C<0>, so nothing will be
50 logged, unless you set C<PERL_ANYEVENT_VERBOSE> to a higher number before
51 starting your program, or change the logging level at runtime with
52 something like:
53
54 use AnyEvent;
55 (AnyEvent::Log::ctx "")->level ("info");
56
57 The design goal behind this module was to keep it simple (and small),
58 but make it powerful enough to be potentially useful for any module, and
59 extensive enough for the most common tasks, such as logging to multiple
60 targets, or being able to log into a database.
61
62 =head1 LOGGING FUNCTIONS
63
64 These functions allow you to log messages. They always use the caller's
65 package as a "logging module/source". Also, the main logging function is
66 callable as C<AnyEvent::log> or C<AE::log> when the C<AnyEvent> module is
67 loaded.
68
69 =over 4
70
71 =cut
72
73 package AnyEvent::Log;
74
75 use Carp ();
76 use POSIX ();
77
78 use AnyEvent (); BEGIN { AnyEvent::common_sense }
79 use AnyEvent::Util ();
80
81 our ($now_int, $now_str1, $now_str2);
82
83 # Format Time, not public - yet?
84 sub ft($) {
85 my $i = int $_[0];
86 my $f = sprintf "%06d", 1e6 * ($_[0] - $i);
87
88 ($now_int, $now_str1, $now_str2) = ($i, split /\x01/, POSIX::strftime "%Y-%m-%d %H:%M:%S.\x01 %z", localtime $i)
89 if $now_int != $i;
90
91 "$now_str1$f$now_str2"
92 }
93
94 our %CTX; # all logging contexts
95
96 # creates a default package context object for the given package
97 sub _pkg_ctx($) {
98 my $ctx = bless [$_[0], (1 << 10) - 1 - 1, {}], "AnyEvent::Log::Ctx";
99
100 # link "parent" package
101 my $pkg = $_[0] =~ /^(.+)::/ ? $1 : "AE::Log::Top";
102
103 $pkg = $CTX{$pkg} ||= &_pkg_ctx ($pkg);
104 $ctx->[2]{$pkg+0} = $pkg;
105
106 $ctx
107 }
108
109 =item AnyEvent::Log::log $level, $msg[, @args]
110
111 Requests logging of the given C<$msg> with the given log level (1..9).
112 You can also use the following strings as log level: C<fatal> (1),
113 C<alert> (2), C<critical> (3), C<error> (4), C<warn> (5), C<note> (6),
114 C<info> (7), C<debug> (8), C<trace> (9).
115
116 For C<fatal> log levels, the program will abort.
117
118 If only a C<$msg> is given, it is logged as-is. With extra C<@args>, the
119 C<$msg> is interpreted as an sprintf format string.
120
121 The C<$msg> should not end with C<\n>, but may if that is convenient for
122 you. Also, multiline messages are handled properly.
123
124 Last not least, C<$msg> might be a code reference, in which case it is
125 supposed to return the message. It will be called only then the message
126 actually gets logged, which is useful if it is costly to create the
127 message in the first place.
128
129 Whether the given message will be logged depends on the maximum log level
130 and the caller's package.
131
132 Note that you can (and should) call this function as C<AnyEvent::log> or
133 C<AE::log>, without C<use>-ing this module if possible (i.e. you don't
134 need any additional functionality), as those functions will load the
135 logging module on demand only. They are also much shorter to write.
136
137 Also, if you optionally generate a lot of debug messages (such as when
138 tracing some code), you should look into using a logger callback and a
139 boolean enabler (see C<logger>, below).
140
141 Example: log something at error level.
142
143 AE::log error => "something";
144
145 Example: use printf-formatting.
146
147 AE::log info => "%5d %-10.10s %s", $index, $category, $msg;
148
149 Example: only generate a costly dump when the message is actually being logged.
150
151 AE::log debug => sub { require Data::Dump; Data::Dump::dump \%cache };
152
153 =cut
154
155 # also allow syslog equivalent names
156 our %STR2LEVEL = (
157 fatal => 1, emerg => 1,
158 alert => 2,
159 critical => 3, crit => 3,
160 error => 4, err => 4,
161 warn => 5, warning => 5,
162 note => 6, notice => 6,
163 info => 7,
164 debug => 8,
165 trace => 9,
166 );
167
168 sub now () { time }
169
170 AnyEvent::post_detect {
171 *now = \&AE::now;
172 };
173
174 our @LEVEL2STR = qw(0 fatal alert crit error warn note info debug trace);
175
176 # time, ctx, level, msg
177 sub _format($$$$) {
178 my $ts = ft $_[0];
179 my $ct = " ";
180
181 my @res;
182
183 for (split /\n/, sprintf "%-5s %s: %s", $LEVEL2STR[$_[2]], $_[1][0], $_[3]) {
184 push @res, "$ts$ct$_\n";
185 $ct = " + ";
186 }
187
188 join "", @res
189 }
190
191 sub _log {
192 my ($ctx, $level, $format, @args) = @_;
193
194 $level = $level > 0 && $level <= 9
195 ? $level+0
196 : $STR2LEVEL{$level} || Carp::croak "$level: not a valid logging level, caught";
197
198 my $mask = 1 << $level;
199
200 my (%seen, @ctx, $now, $fmt);
201
202 do
203 {
204 # skip if masked
205 if ($ctx->[1] & $mask && !$seen{$ctx+0}++) {
206 if ($ctx->[3]) {
207 # logging target found
208
209 # now get raw message, unless we have it already
210 unless ($now) {
211 $format = $format->() if ref $format;
212 $format = sprintf $format, @args if @args;
213 $format =~ s/\n$//;
214 $now = AE::now;
215 };
216
217 # format msg
218 my $str = $ctx->[4]
219 ? $ctx->[4]($now, $_[0], $level, $format)
220 : $fmt ||= _format $now, $_[0], $level, $format;
221
222 $ctx->[3]($str);
223 }
224
225 # not masked, not consumed - propagate to parent contexts
226 push @ctx, values %{ $ctx->[2] };
227 }
228 }
229 while $ctx = pop @ctx;
230
231 exit 1 if $level <= 1;
232 }
233
234 sub log($$;@) {
235 _log
236 $CTX{ (caller)[0] } ||= _pkg_ctx +(caller)[0],
237 @_;
238 }
239
240 *AnyEvent::log = *AE::log = \&log;
241
242 =item $logger = AnyEvent::Log::logger $level[, \$enabled]
243
244 Creates a code reference that, when called, acts as if the
245 C<AnyEvent::Log::log> function was called at this point with the givne
246 level. C<$logger> is passed a C<$msg> and optional C<@args>, just as with
247 the C<AnyEvent::Log::log> function:
248
249 my $debug_log = AnyEvent::Log::logger "debug";
250
251 $debug_log->("debug here");
252 $debug_log->("%06d emails processed", 12345);
253 $debug_log->(sub { $obj->as_string });
254
255 The idea behind this function is to decide whether to log before actually
256 logging - when the C<logger> function is called once, but the returned
257 logger callback often, then this can be a tremendous speed win.
258
259 Despite this speed advantage, changes in logging configuration will
260 still be reflected by the logger callback, even if configuration changes
261 I<after> it was created.
262
263 To further speed up logging, you can bind a scalar variable to the logger,
264 which contains true if the logger should be called or not - if it is
265 false, calling the logger can be safely skipped. This variable will be
266 updated as long as C<$logger> is alive.
267
268 Full example:
269
270 # near the init section
271 use AnyEvent::Log;
272
273 my $debug_log = AnyEvent:Log::logger debug => \my $debug;
274
275 # and later in your program
276 $debug_log->("yo, stuff here") if $debug;
277
278 $debug and $debug_log->("123");
279
280 Note: currently the enabled var is always true - that will be fixed in a
281 future version :)
282
283 =cut
284
285 our %LOGGER;
286
287 # re-assess logging status for all loggers
288 sub _reassess {
289 for (@_ ? $LOGGER{$_[0]} : values %LOGGER) {
290 my ($ctx, $level, $renabled) = @$_;
291
292 # to detect whether a message would be logged, we # actually
293 # try to log one and die. this isn't fast, but we can be
294 # sure that the logging decision is correct :)
295
296 $$renabled = !eval {
297 local $SIG{__DIE__};
298
299 _log $ctx, $level, sub { die };
300
301 1
302 };
303
304 $$renabled = 1; # TODO
305 }
306 }
307
308 sub _logger($;$) {
309 my ($ctx, $level, $renabled) = @_;
310
311 $renabled ||= \my $enabled;
312
313 $$renabled = 1;
314
315 my $logger = [$ctx, $level, $renabled];
316
317 $LOGGER{$logger+0} = $logger;
318
319 _reassess $logger+0;
320
321 my $guard = AnyEvent::Util::guard {
322 # "clean up"
323 delete $LOGGER{$logger+0};
324 };
325
326 sub {
327 $guard if 0; # keep guard alive, but don't cause runtime overhead
328
329 _log $ctx, $level, @_
330 if $$renabled;
331 }
332 }
333
334 sub logger($;$) {
335 _logger
336 $CTX{ (caller)[0] } ||= _pkg_ctx +(caller)[0],
337 @_
338 }
339
340 =back
341
342 =head1 LOGGING CONTEXTS
343
344 This module associates every log message with a so-called I<logging
345 context>, based on the package of the caller. Every perl package has its
346 own logging context.
347
348 A logging context has three major responsibilities: filtering, logging and
349 propagating the message.
350
351 For the first purpose, filtering, each context has a set of logging
352 levels, called the log level mask. Messages not in the set will be ignored
353 by this context (masked).
354
355 For logging, the context stores a formatting callback (which takes the
356 timestamp, context, level and string message and formats it in the way
357 it should be logged) and a logging callback (which is responsible for
358 actually logging the formatted message and telling C<AnyEvent::Log>
359 whether it has consumed the message, or whether it should be propagated).
360
361 For propagation, a context can have any number of attached I<parent
362 contexts>. Any message that is neither masked by the logging mask nor
363 masked by the logging callback returning true will be passed to all parent
364 contexts.
365
366 Each call to a logging function will log the message at most once per
367 context, so it does not matter (much) if there are cycles or if the
368 message can arrive at the same context via multiple paths.
369
370 =head2 DEFAULTS
371
372 By default, all logging contexts have an full set of log levels ("all"), a
373 disabled logging callback and the default formatting callback.
374
375 Package contexts have the package name as logging title by default.
376
377 They have exactly one parent - the context of the "parent" package. The
378 parent package is simply defined to be the package name without the last
379 component, i.e. C<AnyEvent::Debug::Wrapped> becomes C<AnyEvent::Debug>,
380 and C<AnyEvent> becomes ... C<AnyEvent::Log::Top> which is the
381 exception of the rule - just like the parent of any package name in
382 Perl is C<main>, the default parent of any toplevel package context is
383 C<AnyEvent::Log::Top>.
384
385 Since perl packages form only an approximate hierarchy, this parent
386 context can of course be removed.
387
388 All other (anonymous) contexts have no parents and an empty title by
389 default.
390
391 When the module is loaded it creates the default context called
392 C<AnyEvent::Log::Default>, which simply logs everything to STDERR and
393 doesn't propagate anything anywhere by default. The purpose of the default
394 context is to provide a convenient place to override the global logging
395 target or to attach additional log targets. It's not meant for filtering.
396
397 It then creates the root context called C<AnyEvent::Log::Root> and
398 sets its log level set to all levels up to the one specified by
399 C<$ENV{PERL_ANYEVENT_VERBOSE}>. It then attached the default logging
400 context to it. The purpose of the root context is to simply provide
401 filtering according to some global log level.
402
403 Finally it creates the toplevel package context called
404 C<AnyEvent::Log::Top> and attached the root context but otherwise leaves
405 it at default config. It's purpose is simply to collect all log messages
406 system-wide.
407
408 These three special contexts can also be referred to by the names
409 C<AE::Log::Default>, C<AE::Log::Root> and C<AE::Log::Top>.
410
411 The effect of all this is that log messages, by default, wander up
412 to the root context where log messages with lower priority then
413 C<$ENV{PERL_ANYEVENT_VERBOSE}> will be filtered away and then to the
414 AnyEvent::Log::Default context to be logged to STDERR.
415
416 Splitting the top level context into three contexts makes it easy to set
417 a global logging level (by modifying the root context), but still allow
418 other contexts to log, for example, their debug and trace messages to the
419 default target despite the global logging level, or to attach additional
420 log targets that log messages, regardless of the global logging level.
421
422 It also makes it easy to replace the default STDERR-logger by something
423 that logs to a file, or to attach additional logging targets.
424
425 =head2 CREATING/FINDING/DESTROYING CONTEXTS
426
427 =over 4
428
429 =item $ctx = AnyEvent::Log::ctx [$pkg]
430
431 This function creates or returns a logging context (which is an object).
432
433 If a package name is given, then the context for that packlage is
434 returned. If it is called without any arguments, then the context for the
435 callers package is returned (i.e. the same context as a C<AE::log> call
436 would use).
437
438 If C<undef> is given, then it creates a new anonymous context that is not
439 tied to any package and is destroyed when no longer referenced.
440
441 =cut
442
443 sub ctx(;$) {
444 my $pkg = @_ ? shift : (caller)[0];
445
446 ref $pkg
447 ? $pkg
448 : defined $pkg
449 ? $CTX{$pkg} ||= AnyEvent::Log::_pkg_ctx $pkg
450 : bless [undef, (1 << 10) - 1 - 1], "AnyEvent::Log::Ctx"
451 }
452
453 =item AnyEvent::Log::reset
454
455 Deletes all contexts and recreates the default hierarchy, i.e. resets the
456 logging subsystem to defaults.
457
458 This can be used to implement config-file (re-)loading: before loading a
459 configuration, reset all contexts.
460
461 =cut
462
463 sub reset {
464 @$_ = () for values %CTX; # just to be sure - to kill circular logging dependencies
465 %CTX = ();
466
467 my $default = ctx undef;
468 $default->title ("AnyEvent::Log::Default");
469 $default->log_cb (sub {
470 print STDERR shift;
471 0
472 });
473 $CTX{"AnyEvent::Log::Default"} = $CTX{"AE::Log::Default"} = $default;
474
475 my $root = ctx undef;
476 $root->title ("AnyEvent::Log::Root");
477 $root->level ($AnyEvent::VERBOSE);
478 $root->attach ($default);
479 $CTX{"AnyEvent::Log::Root"} = $CTX{"AE::Log::Root"} = $root;
480
481 my $top = ctx undef;
482 $top->title ("AnyEvent::Log::Top");
483 $top->attach ($root);
484 $CTX{"AnyEvent::Log::Top"} = $CTX{"AE::Log::Top"} = $top;
485 }
486
487 AnyEvent::Log::reset;
488
489 package AnyEvent::Log::Default;
490 package AE::Log::Default;
491 package AnyEvent::Log::Root;
492 package AE::Log::Root;
493 package AnyEvent::Log::Top;
494 package AE::Log::Top;
495
496 =back
497
498 =cut
499
500 package AnyEvent::Log::Ctx;
501
502 # 0 1 2 3 4
503 # [$title, $level, %$parents, &$logcb, &$fmtcb]
504
505 =head2 CONFIGURING A LOG CONTEXT
506
507 The following methods can be used to configure the logging context.
508
509 =over 4
510
511 =item $ctx->title ([$new_title])
512
513 Returns the title of the logging context - this is the package name, for
514 package contexts, and a user defined string for all others.
515
516 If C<$new_title> is given, then it replaces the package name or title.
517
518 =cut
519
520 sub title {
521 $_[0][0] = $_[1] if @_ > 1;
522 $_[0][0]
523 }
524
525 =back
526
527 =head3 LOGGING LEVELS
528
529 The following methods deal with the logging level set associated with the
530 log context.
531
532 The most common method to use is probably C<< $ctx->level ($level) >>,
533 which configures the specified and any higher priority levels.
534
535 All functions which accept a list of levels also accept the special string
536 C<all> which expands to all logging levels.
537
538 =over 4
539
540 =item $ctx->levels ($level[, $level...)
541
542 Enables logging for the given levels and disables it for all others.
543
544 =item $ctx->level ($level)
545
546 Enables logging for the given level and all lower level (higher priority)
547 ones. In addition to normal logging levels, specifying a level of C<0> or
548 C<off> disables all logging for this level.
549
550 Example: log warnings, errors and higher priority messages.
551
552 $ctx->level ("warn");
553 $ctx->level (5); # same thing, just numeric
554
555 =item $ctx->enable ($level[, $level...])
556
557 Enables logging for the given levels, leaving all others unchanged.
558
559 =item $ctx->disable ($level[, $level...])
560
561 Disables logging for the given levels, leaving all others unchanged.
562
563 =cut
564
565 sub _lvl_lst {
566 map {
567 $_ > 0 && $_ <= 9 ? $_+0
568 : $_ eq "all" ? (1 .. 9)
569 : $STR2LEVEL{$_} || Carp::croak "$_: not a valid logging level, caught"
570 } @_
571 }
572
573 our $NOP_CB = sub { 0 };
574
575 sub levels {
576 my $ctx = shift;
577 $ctx->[1] = 0;
578 $ctx->[1] |= 1 << $_
579 for &_lvl_lst;
580 AnyEvent::Log::_reassess;
581 }
582
583 sub level {
584 my $ctx = shift;
585 my $lvl = $_[0] =~ /^(?:0|off|none)$/ ? 0 : (_lvl_lst $_[0])[-1];
586
587 $ctx->[1] = ((1 << $lvl) - 1) << 1;
588 AnyEvent::Log::_reassess;
589 }
590
591 sub enable {
592 my $ctx = shift;
593 $ctx->[1] |= 1 << $_
594 for &_lvl_lst;
595 AnyEvent::Log::_reassess;
596 }
597
598 sub disable {
599 my $ctx = shift;
600 $ctx->[1] &= ~(1 << $_)
601 for &_lvl_lst;
602 AnyEvent::Log::_reassess;
603 }
604
605 =back
606
607 =head3 PARENT CONTEXTS
608
609 The following methods attach and detach another logging context to a
610 logging context.
611
612 Log messages are propagated to all parent contexts, unless the logging
613 callback consumes the message.
614
615 =over 4
616
617 =item $ctx->attach ($ctx2[, $ctx3...])
618
619 Attaches the given contexts as parents to this context. It is not an error
620 to add a context twice (the second add will be ignored).
621
622 A context can be specified either as package name or as a context object.
623
624 =item $ctx->detach ($ctx2[, $ctx3...])
625
626 Removes the given parents from this context - it's not an error to attempt
627 to remove a context that hasn't been added.
628
629 A context can be specified either as package name or as a context object.
630
631 =item $ctx->parents ($ctx2[, $ctx3...])
632
633 Replaces all parents attached to this context by the ones given.
634
635 =cut
636
637 sub attach {
638 my $ctx = shift;
639
640 $ctx->[2]{$_+0} = $_
641 for map { AnyEvent::Log::ctx $_ } @_;
642 }
643
644 sub detach {
645 my $ctx = shift;
646
647 delete $ctx->[2]{$_+0}
648 for map { AnyEvent::Log::ctx $_ } @_;
649 }
650
651 sub parents {
652 undef $_[0][2];
653 &attach;
654 }
655
656 =back
657
658 =head3 MESSAGE LOGGING
659
660 The following methods configure how the logging context actually does
661 the logging (which consists of formatting the message and printing it or
662 whatever it wants to do with it) and also allows you to log messages
663 directly to a context, without going via your package context.
664
665 =over 4
666
667 =item $ctx->log_cb ($cb->($str))
668
669 Replaces the logging callback on the context (C<undef> disables the
670 logging callback).
671
672 The logging callback is responsible for handling formatted log messages
673 (see C<fmt_cb> below) - normally simple text strings that end with a
674 newline (and are possibly multiline themselves).
675
676 It also has to return true iff it has consumed the log message, and false
677 if it hasn't. Consuming a message means that it will not be sent to any
678 parent context. When in doubt, return C<0> from your logging callback.
679
680 Example: a very simple logging callback, simply dump the message to STDOUT
681 and do not consume it.
682
683 $ctx->log_cb (sub { print STDERR shift; 0 });
684
685 You can filter messages by having a log callback that simply returns C<1>
686 and does not do anything with the message, but this counts as "message
687 being logged" and might not be very efficient.
688
689 Example: propagate all messages except for log levels "debug" and
690 "trace". The messages will still be generated, though, which can slow down
691 your program.
692
693 $ctx->levels ("debug", "trace");
694 $ctx->log_cb (sub { 1 }); # do not log, but eat debug and trace messages
695
696 =item $ctx->fmt_cb ($fmt_cb->($timestamp, $ctx, $level, $message))
697
698 Replaces the formatting callback on the context (C<undef> restores the
699 default formatter).
700
701 The callback is passed the (possibly fractional) timestamp, the original
702 logging context, the (numeric) logging level and the raw message string and needs to
703 return a formatted log message. In most cases this will be a string, but
704 it could just as well be an array reference that just stores the values.
705
706 Example: format just the raw message, with numeric log level in angle
707 brackets.
708
709 $ctx->fmt_cb (sub {
710 my ($time, $ctx, $lvl, $msg) = @_;
711
712 "<$lvl>$msg\n"
713 });
714
715 Example: return an array reference with just the log values, and use
716 C<PApp::SQL::sql_exec> to store the emssage in a database.
717
718 $ctx->fmt_cb (sub { \@_ });
719 $ctx->log_cb (sub {
720 my ($msg) = @_;
721
722 sql_exec "insert into log (when, subsys, prio, msg) values (?, ?, ?, ?)",
723 $msg->[0] + 0,
724 "$msg->[1]",
725 $msg->[2] + 0,
726 "$msg->[3]";
727
728 0
729 });
730
731 =cut
732
733 sub log_cb {
734 my ($ctx, $cb) = @_;
735
736 $ctx->[3] = $cb;
737 }
738
739 sub fmt_cb {
740 my ($ctx, $cb) = @_;
741
742 $ctx->[4] = $cb;
743 }
744
745 =item $ctx->log ($level, $msg[, @params])
746
747 Same as C<AnyEvent::Log::log>, but uses the given context as log context.
748
749 =item $logger = $ctx->logger ($level[, \$enabled])
750
751 Same as C<AnyEvent::Log::logger>, but uses the given context as log
752 context.
753
754 =cut
755
756 *log = \&AnyEvent::Log::_log;
757 *logger = \&AnyEvent::Log::_logger;
758
759 1;
760
761 =back
762
763 =head1 AUTHOR
764
765 Marc Lehmann <schmorp@schmorp.de>
766 http://home.schmorp.de/
767
768 =cut