ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent/Log.pm
(Generate patch)

Comparing AnyEvent/lib/AnyEvent/Log.pm (file contents):
Revision 1.43 by root, Mon Sep 5 07:21:54 2011 UTC vs.
Revision 1.47 by root, Sun Mar 11 20:39:10 2012 UTC

6 6
7Simple uses: 7Simple uses:
8 8
9 use AnyEvent; 9 use AnyEvent;
10 10
11 AE::log debug => "hit my knee"; 11 AE::log trace => "going to call function abc";
12 AE::log warn => "it's a bit too hot"; 12 AE::log debug => "the function returned 3";
13 AE::log error => "the flag was false!"; 13 AE::log info => "file soandso successfully deleted";
14 AE::log fatal => "the bit toggled! run!"; # never returns 14 AE::log note => "wanted to create config, but config was alraedy created";
15 AE::log warn => "couldn't delete the file";
16 AE::log error => "failed to retrieve data";
17 AE::log crit => "the battery temperature is too hot";
18 AE::log alert => "the battery died";
19 AE::log fatal => "no config found, cannot continue"; # never returns
15 20
16 # available log levels in order: 21Log level overview:
17 # fatal alert critical error warn note info debug trace
18
19"Complex" uses (for speed sensitive code):
20
21 use AnyEvent::Log;
22
23 my $tracer = AnyEvent::Log::logger trace => \$my $trace;
24
25 $tracer->("i am here") if $trace;
26 $tracer->(sub { "lots of data: " . Dumper $self }) if $trace;
27
28Configuration (also look at the EXAMPLES section):
29
30 # set logging for the current package to errors and higher only
31 AnyEvent::Log::ctx->level ("error");
32
33 # set logging level to suppress anything below "notice"
34 $AnyEvent::Log::FILTER->level ("notice");
35
36 # send all critical and higher priority messages to syslog,
37 # regardless of (most) other settings
38 $AnyEvent::Log::COLLECT->attach (new AnyEvent::Log::Ctx
39 level => "critical",
40 log_to_syslog => "user",
41 );
42
43=head1 DESCRIPTION
44
45This module implements a relatively simple "logging framework". It doesn't
46attempt to be "the" logging solution or even "a" logging solution for
47AnyEvent - AnyEvent simply creates logging messages internally, and this
48module more or less exposes the mechanism, with some extra spiff to allow
49using it from other modules as well.
50
51Remember that the default verbosity level is C<0> (C<off>), so nothing
52will be logged, unless you set C<PERL_ANYEVENT_VERBOSE> to a higher number
53before starting your program, or change the logging level at runtime with
54something like:
55
56 use AnyEvent::Log;
57 $AnyEvent::Log::FILTER->level ("info");
58
59The design goal behind this module was to keep it simple (and small),
60but make it powerful enough to be potentially useful for any module, and
61extensive enough for the most common tasks, such as logging to multiple
62targets, or being able to log into a database.
63
64The module is also usable before AnyEvent itself is initialised, in which
65case some of the functionality might be reduced.
66
67The amount of documentation might indicate otherwise, but the runtime part
68of the module is still just below 300 lines of code.
69
70=head1 LOGGING LEVELS
71
72Logging levels in this module range from C<1> (highest priority) to C<9>
73(lowest priority). Note that the lowest numerical value is the highest
74priority, so when this document says "higher priority" it means "lower
75numerical value".
76
77Instead of specifying levels by name you can also specify them by aliases:
78 22
79 LVL NAME SYSLOG PERL NOTE 23 LVL NAME SYSLOG PERL NOTE
80 1 fatal emerg exit system unusable, aborts program! 24 1 fatal emerg exit system unusable, aborts program!
81 2 alert failure in primary system 25 2 alert failure in primary system
82 3 critical crit failure in backup system 26 3 critical crit failure in backup system
85 6 note notice unusual conditions 29 6 note notice unusual conditions
86 7 info normal messages, no action required 30 7 info normal messages, no action required
87 8 debug debugging messages for development 31 8 debug debugging messages for development
88 9 trace copious tracing output 32 9 trace copious tracing output
89 33
34"Complex" uses (for speed sensitive code, e.g. trace/debug messages):
35
36 use AnyEvent::Log;
37
38 my $tracer = AnyEvent::Log::logger trace => \$my $trace;
39
40 $tracer->("i am here") if $trace;
41 $tracer->(sub { "lots of data: " . Dumper $self }) if $trace;
42
43Configuration (also look at the EXAMPLES section):
44
45 # set logging for the current package to errors and higher only
46 AnyEvent::Log::ctx->level ("error");
47
48 # set logging level to suppress anything below "notice"
49 $AnyEvent::Log::FILTER->level ("notice");
50
51 # send all critical and higher priority messages to syslog,
52 # regardless of (most) other settings
53 $AnyEvent::Log::COLLECT->attach (new AnyEvent::Log::Ctx
54 level => "critical",
55 log_to_syslog => "user",
56 );
57
58=head1 DESCRIPTION
59
60This module implements a relatively simple "logging framework". It doesn't
61attempt to be "the" logging solution or even "a" logging solution for
62AnyEvent - AnyEvent simply creates logging messages internally, and this
63module more or less exposes the mechanism, with some extra spiff to allow
64using it from other modules as well.
65
66Remember that the default verbosity level is C<0> (C<off>), so nothing
67will be logged, unless you set C<PERL_ANYEVENT_VERBOSE> to a higher number
68before starting your program, or change the logging level at runtime with
69something like:
70
71 use AnyEvent::Log;
72 $AnyEvent::Log::FILTER->level ("info");
73
74The design goal behind this module was to keep it simple (and small),
75but make it powerful enough to be potentially useful for any module, and
76extensive enough for the most common tasks, such as logging to multiple
77targets, or being able to log into a database.
78
79The module is also usable before AnyEvent itself is initialised, in which
80case some of the functionality might be reduced.
81
82The amount of documentation might indicate otherwise, but the runtime part
83of the module is still just below 300 lines of code.
84
85=head1 LOGGING LEVELS
86
87Logging levels in this module range from C<1> (highest priority) to C<9>
88(lowest priority). Note that the lowest numerical value is the highest
89priority, so when this document says "higher priority" it means "lower
90numerical value".
91
92Instead of specifying levels by name you can also specify them by aliases:
93
94 LVL NAME SYSLOG PERL NOTE
95 1 fatal emerg exit system unusable, aborts program!
96 2 alert failure in primary system
97 3 critical crit failure in backup system
98 4 error err die non-urgent program errors, a bug
99 5 warn warning possible problem, not necessarily error
100 6 note notice unusual conditions
101 7 info normal messages, no action required
102 8 debug debugging messages for development
103 9 trace copious tracing output
104
90As you can see, some logging levels have multiple aliases - the first one 105As you can see, some logging levels have multiple aliases - the first one
91is the "official" name, the second one the "syslog" name (if it differs) 106is the "official" name, the second one the "syslog" name (if it differs)
92and the third one the "perl" name, suggesting (only!) that you log C<die> 107and the third one the "perl" name, suggesting (only!) that you log C<die>
93messages at C<error> priority. The NOTE column tries to provide some 108messages at C<error> priority. The NOTE column tries to provide some
94rationale on how to chose a logging level. 109rationale on how to chose a logging level.
119package AnyEvent::Log; 134package AnyEvent::Log;
120 135
121use Carp (); 136use Carp ();
122use POSIX (); 137use POSIX ();
123 138
139# layout of a context
140# 0 1 2 3 4, 5
141# [$title, $level, %$slaves, &$logcb, &$fmtcb, $cap]
142
124use AnyEvent (); BEGIN { AnyEvent::common_sense } 143use AnyEvent (); BEGIN { AnyEvent::common_sense }
125#use AnyEvent::Util (); need to load this in a delayed fashion, as it uses AE::log 144#use AnyEvent::Util (); need to load this in a delayed fashion, as it uses AE::log
126 145
127our $VERSION = $AnyEvent::VERSION; 146our $VERSION = $AnyEvent::VERSION;
128 147
172 191
173Last not least, C<$msg> might be a code reference, in which case it is 192Last not least, C<$msg> might be a code reference, in which case it is
174supposed to return the message. It will be called only then the message 193supposed to return the message. It will be called only then the message
175actually gets logged, which is useful if it is costly to create the 194actually gets logged, which is useful if it is costly to create the
176message in the first place. 195message in the first place.
196
197This function takes care of saving and restoring C<$!> and C<$@>, so you
198don't have to.
177 199
178Whether the given message will be logged depends on the maximum log level 200Whether the given message will be logged depends on the maximum log level
179and the caller's package. The return value can be used to ensure that 201and the caller's package. The return value can be used to ensure that
180messages or not "lost" - for example, when L<AnyEvent::Debug> detects a 202messages or not "lost" - for example, when L<AnyEvent::Debug> detects a
181runtime error it tries to log it at C<die> level, but if that message is 203runtime error it tries to log it at C<die> level, but if that message is
262 ? $level+0 284 ? $level+0
263 : $STR2LEVEL{$level} || Carp::croak "$level: not a valid logging level, caught"; 285 : $STR2LEVEL{$level} || Carp::croak "$level: not a valid logging level, caught";
264 286
265 my $mask = 1 << $level; 287 my $mask = 1 << $level;
266 288
267 my ($success, %seen, @ctx, $now, $fmt); 289 my ($success, %seen, @ctx, $now, @fmt);
268 290
269 do 291 do
270 { 292 {
271 # skip if masked 293 # if !ref, then it's a level number
294 if (!ref $ctx) {
295 $level = $ctx;
272 if ($ctx->[1] & $mask && !$seen{$ctx+0}++) { 296 } elsif ($ctx->[1] & $mask and !$seen{$ctx+0}++) {
297 # logging/recursing into this context
298
299 # level cap
300 if ($ctx->[5] > $level) {
301 push @ctx, $level; # restore level when going up in tree
302 $level = $ctx->[5];
303 }
304
305 # log if log cb
273 if ($ctx->[3]) { 306 if ($ctx->[3]) {
274 # logging target found 307 # logging target found
308
309 local ($!, $@);
275 310
276 # now get raw message, unless we have it already 311 # now get raw message, unless we have it already
277 unless ($now) { 312 unless ($now) {
278 $format = $format->() if ref $format; 313 $format = $format->() if ref $format;
279 $format = sprintf $format, @args if @args; 314 $format = sprintf $format, @args if @args;
282 }; 317 };
283 318
284 # format msg 319 # format msg
285 my $str = $ctx->[4] 320 my $str = $ctx->[4]
286 ? $ctx->[4]($now, $_[0], $level, $format) 321 ? $ctx->[4]($now, $_[0], $level, $format)
287 : ($fmt ||= _format $now, $_[0], $level, $format); 322 : ($fmt[$level] ||= _format $now, $_[0], $level, $format);
288 323
289 $success = 1; 324 $success = 1;
290 325
291 $ctx->[3]($str) 326 $ctx->[3]($str)
292 or push @ctx, values %{ $ctx->[2] }; # not consumed - propagate 327 or push @ctx, values %{ $ctx->[2] }; # not consumed - propagate
596package AnyEvent::Log::COLLECT; 631package AnyEvent::Log::COLLECT;
597package AE::Log::COLLECT; 632package AE::Log::COLLECT;
598 633
599package AnyEvent::Log::Ctx; 634package AnyEvent::Log::Ctx;
600 635
601# 0 1 2 3 4
602# [$title, $level, %$slaves, &$logcb, &$fmtcb]
603
604=item $ctx = new AnyEvent::Log::Ctx methodname => param... 636=item $ctx = new AnyEvent::Log::Ctx methodname => param...
605 637
606This is a convenience constructor that makes it simpler to construct 638This is a convenience constructor that makes it simpler to construct
607anonymous logging contexts. 639anonymous logging contexts.
608 640
695 727
696=item $ctx->disable ($level[, $level...]) 728=item $ctx->disable ($level[, $level...])
697 729
698Disables logging for the given levels, leaving all others unchanged. 730Disables logging for the given levels, leaving all others unchanged.
699 731
732=item $ctx->cap ($level)
733
734Caps the maximum priority to the given level, for all messages logged
735to, or passing through, this context. That is, while this doesn't affect
736whether a message is logged or passed on, the maximum priority of messages
737will be limited to the specified level - messages with a higher priority
738will be set to the specified priority.
739
740Another way to view this is that C<< ->level >> filters out messages with
741a too low priority, while C<< ->cap >> modifies messages with a too high
742priority.
743
744This is useful when different log targets have different interpretations
745of priority. For example, for a specific command line program, a wrong
746command line switch might well result in a C<fatal> log message, while the
747same message, logged to syslog, is likely I<not> fatal to the system or
748syslog facility as a whole, but more likely a mere C<error>.
749
750This can be modeled by having a stderr logger that logs messages "as-is"
751and a syslog logger that logs messages with a level cap of, say, C<error>,
752or, for truly system-critical components, actually C<critical>.
753
700=cut 754=cut
701 755
702sub _lvl_lst { 756sub _lvl_lst {
703 map { 757 map {
704 $_ > 0 && $_ <= 9 ? $_+0 758 $_ > 0 && $_ <= 9 ? $_+0
705 : $_ eq "all" ? (1 .. 9) 759 : $_ eq "all" ? (1 .. 9)
706 : $STR2LEVEL{$_} || Carp::croak "$_: not a valid logging level, caught" 760 : $STR2LEVEL{$_} || Carp::croak "$_: not a valid logging level, caught"
707 } @_ 761 } @_
708} 762}
709 763
764sub _lvl {
765 $_[0] =~ /^(?:0|off|none)$/ ? 0 : (_lvl_lst $_[0])[-1]
766}
767
710our $NOP_CB = sub { 0 }; 768our $NOP_CB = sub { 0 };
711 769
712sub levels { 770sub levels {
713 my $ctx = shift; 771 my $ctx = shift;
714 $ctx->[1] = 0; 772 $ctx->[1] = 0;
717 AnyEvent::Log::_reassess; 775 AnyEvent::Log::_reassess;
718} 776}
719 777
720sub level { 778sub level {
721 my $ctx = shift; 779 my $ctx = shift;
722 my $lvl = $_[0] =~ /^(?:0|off|none)$/ ? 0 : (_lvl_lst $_[0])[-1];
723
724 $ctx->[1] = ((1 << $lvl) - 1) << 1; 780 $ctx->[1] = ((1 << &_lvl) - 1) << 1;
725 AnyEvent::Log::_reassess; 781 AnyEvent::Log::_reassess;
726} 782}
727 783
728sub enable { 784sub enable {
729 my $ctx = shift; 785 my $ctx = shift;
737 $ctx->[1] &= ~(1 << $_) 793 $ctx->[1] &= ~(1 << $_)
738 for &_lvl_lst; 794 for &_lvl_lst;
739 AnyEvent::Log::_reassess; 795 AnyEvent::Log::_reassess;
740} 796}
741 797
798sub cap {
799 my $ctx = shift;
800 $ctx->[5] = &_lvl;
801}
802
742=back 803=back
743 804
744=head3 SLAVE CONTEXTS 805=head3 SLAVE CONTEXTS
745 806
746The following methods attach and detach another logging context to a 807The following methods attach and detach another logging context to a
1076=item C<nolog> 1137=item C<nolog>
1077 1138
1078Configures the context to not log anything by itself, which is the 1139Configures the context to not log anything by itself, which is the
1079default. Same as C<< $ctx->log_cb (undef) >>. 1140default. Same as C<< $ctx->log_cb (undef) >>.
1080 1141
1142=item C<cap=>I<level>
1143
1144Caps logging messages entering this context at the given level, i.e.
1145reduces the priority of messages with higher priority than this level. The
1146default is C<0> (or C<off>), meaning the priority will not be touched.
1147
1081=item C<0> or C<off> 1148=item C<0> or C<off>
1082 1149
1083Sets the logging level of the context ot C<0>, i.e. all messages will be 1150Sets the logging level of the context to C<0>, i.e. all messages will be
1084filtered out. 1151filtered out.
1085 1152
1086=item C<all> 1153=item C<all>
1087 1154
1088Enables all logging levels, i.e. filtering will effectively be switched 1155Enables all logging levels, i.e. filtering will effectively be switched
1130 1197
1131Attaches the named context as slave to the context. 1198Attaches the named context as slave to the context.
1132 1199
1133=item C<+> 1200=item C<+>
1134 1201
1135A line C<+> detaches all contexts, i.e. clears the slave list from the 1202A lone C<+> detaches all contexts, i.e. clears the slave list from the
1136context. Anonymous (C<%name>) contexts have no attached slaves by default, 1203context. Anonymous (C<%name>) contexts have no attached slaves by default,
1137but package contexts have the parent context as slave by default. 1204but package contexts have the parent context as slave by default.
1138 1205
1139Example: log messages from My::Module to a file, do not send them to the 1206Example: log messages from My::Module to a file, do not send them to the
1140default log collector. 1207default log collector.
1171 1238
1172 my $pkg = sub { 1239 my $pkg = sub {
1173 $_[0] eq "log" ? $LOG 1240 $_[0] eq "log" ? $LOG
1174 : $_[0] eq "filter" ? $FILTER 1241 : $_[0] eq "filter" ? $FILTER
1175 : $_[0] eq "collect" ? $COLLECT 1242 : $_[0] eq "collect" ? $COLLECT
1176 : $_[0] =~ /^%(.+)$/ ? ($anon{$1} ||= ctx undef) 1243 : $_[0] =~ /^%(.+)$/ ? ($anon{$1} ||= do { my $ctx = ctx undef; $ctx->[0] = $_[0]; $ctx })
1177 : $_[0] =~ /^(.*?)(?:::)?$/ ? ctx "$1" # egad :/ 1244 : $_[0] =~ /^(.*?)(?:::)?$/ ? ctx "$1" # egad :/
1178 : die # never reached? 1245 : die # never reached?
1179 }; 1246 };
1180 1247
1181 /\G[[:space:]]+/gc; # skip initial whitespace 1248 /\G[[:space:]]+/gc; # skip initial whitespace
1187 while (/\G((?:[^,:[:space:]]+|::|\\.)+)/gc) { 1254 while (/\G((?:[^,:[:space:]]+|::|\\.)+)/gc) {
1188 for ("$1") { 1255 for ("$1") {
1189 if ($_ eq "stderr" ) { $ctx->log_to_warn; 1256 if ($_ eq "stderr" ) { $ctx->log_to_warn;
1190 } elsif (/^file=(.+)/ ) { $ctx->log_to_file ("$1"); 1257 } elsif (/^file=(.+)/ ) { $ctx->log_to_file ("$1");
1191 } elsif (/^path=(.+)/ ) { $ctx->log_to_path ("$1"); 1258 } elsif (/^path=(.+)/ ) { $ctx->log_to_path ("$1");
1192 } elsif (/syslog(?:=(.*))?/ ) { require Sys::Syslog; $ctx->log_to_syslog ($1); 1259 } elsif (/^syslog(?:=(.*))?/ ) { require Sys::Syslog; $ctx->log_to_syslog ("$1");
1193 } elsif ($_ eq "nolog" ) { $ctx->log_cb (undef); 1260 } elsif ($_ eq "nolog" ) { $ctx->log_cb (undef);
1261 } elsif (/^cap=(.+)/ ) { $ctx->cap ("$1");
1194 } elsif (/^\+(.+)$/ ) { $ctx->attach ($pkg->("$1")); 1262 } elsif (/^\+(.+)$/ ) { $ctx->attach ($pkg->("$1"));
1195 } elsif ($_ eq "+" ) { $ctx->slaves; 1263 } elsif ($_ eq "+" ) { $ctx->slaves;
1196 } elsif ($_ eq "off" or $_ eq "0") { $ctx->level (0); 1264 } elsif ($_ eq "off" or $_ eq "0") { $ctx->level (0);
1197 } elsif ($_ eq "all" ) { $ctx->level ("all"); 1265 } elsif ($_ eq "all" ) { $ctx->level ("all");
1198 } elsif ($_ eq "level" ) { $ctx->level ("all"); $level = "level"; 1266 } elsif ($_ eq "level" ) { $ctx->level ("all"); $level = "level";
1266 1334
1267 PERL_ANYEVENT_LOG=%filelogger=file=/some/path:collect=+%filelogger 1335 PERL_ANYEVENT_LOG=%filelogger=file=/some/path:collect=+%filelogger
1268 1336
1269In both cases, messages are still written to STDERR. 1337In both cases, messages are still written to STDERR.
1270 1338
1339=item Additionally log all messages with C<warn> and higher priority to
1340C<syslog>, but cap at C<error>.
1341
1342This logs all messages to the default log target, but also logs messages
1343with priority C<warn> or higher (and not filtered otherwise) to syslog
1344facility C<user>. Messages with priority higher than C<error> will be
1345logged with level C<error>.
1346
1347 $AnyEvent::Log::LOG->attach (
1348 new AnyEvent::Log::Ctx
1349 level => "warn",
1350 cap => "error",
1351 syslog => "user",
1352 );
1353
1354 PERL_ANYEVENT_LOG=log=+%syslog:%syslog=warn,cap=error,syslog
1355
1271=item Write trace messages (only) from L<AnyEvent::Debug> to the default logging target(s). 1356=item Write trace messages (only) from L<AnyEvent::Debug> to the default logging target(s).
1272 1357
1273Attach the C<$AnyEvent::Log::LOG> context to the C<AnyEvent::Debug> 1358Attach the C<$AnyEvent::Log::LOG> context to the C<AnyEvent::Debug>
1274context - this simply circumvents the global filtering for trace messages. 1359context - this simply circumvents the global filtering for trace messages.
1275 1360

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines