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.44 by root, Mon Sep 26 11:32:19 2011 UTC vs.
Revision 1.49 by root, Thu Mar 22 01:03:57 2012 UTC

9 use AnyEvent; 9 use AnyEvent;
10 10
11 AE::log trace => "going to call function abc"; 11 AE::log trace => "going to call function abc";
12 AE::log debug => "the function returned 3"; 12 AE::log debug => "the function returned 3";
13 AE::log info => "file soandso successfully deleted"; 13 AE::log info => "file soandso successfully deleted";
14 AE::log note => "wanted to create config, but config was alraedy created"; 14 AE::log note => "wanted to create config, but config was already created";
15 AE::log warn => "couldn't delete the file"; 15 AE::log warn => "couldn't delete the file";
16 AE::log error => "failed to retrieve data"; 16 AE::log error => "failed to retrieve data";
17 AE::log crit => "the battery temperature is too hot"; 17 AE::log crit => "the battery temperature is too hot";
18 AE::log alert => "the battery died"; 18 AE::log alert => "the battery died";
19 AE::log fatal => "no config found, cannot continue"; # never returns 19 AE::log fatal => "no config found, cannot continue"; # never returns
61attempt to be "the" logging solution or even "a" logging solution for 61attempt to be "the" logging solution or even "a" logging solution for
62AnyEvent - AnyEvent simply creates logging messages internally, and this 62AnyEvent - AnyEvent simply creates logging messages internally, and this
63module more or less exposes the mechanism, with some extra spiff to allow 63module more or less exposes the mechanism, with some extra spiff to allow
64using it from other modules as well. 64using it from other modules as well.
65 65
66Remember that the default verbosity level is C<0> (C<off>), so nothing 66Remember that the default verbosity level is C<3> (C<critical>), so little
67will be logged, unless you set C<PERL_ANYEVENT_VERBOSE> to a higher number 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 68before starting your program, or change the logging level at runtime with
69something like: 69something like:
70 70
71 use AnyEvent::Log; 71 use AnyEvent::Log;
106is 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)
107and 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>
108messages at C<error> priority. The NOTE column tries to provide some 108messages at C<error> priority. The NOTE column tries to provide some
109rationale on how to chose a logging level. 109rationale on how to chose a logging level.
110 110
111As a rough guideline, levels 1..3 are primarily meant for users of 111As a rough guideline, levels 1..3 are primarily meant for users of the
112the program (admins, staff), and are the only logged to STDERR by 112program (admins, staff), and are the only ones logged to STDERR by
113default. Levels 4..6 are meant for users and developers alike, while 113default. Levels 4..6 are meant for users and developers alike, while
114levels 7..9 are usually meant for developers. 114levels 7..9 are usually meant for developers.
115 115
116You can normally only log a single message at highest priority level 116You can normally only log a message once at highest priority level (C<1>,
117(C<1>, C<fatal>), because logging a fatal message will also quit the 117C<fatal>), because logging a fatal message will also quit the program - so
118program - so use it sparingly :) 118use it sparingly :)
119 119
120Some methods also offer some extra levels, such as C<0>, C<off>, C<none> 120Some methods also offer some extra levels, such as C<0>, C<off>, C<none>
121or C<all> - these are only valid in the methods they are documented for. 121or C<all> - these are only valid for the methods that documented them.
122 122
123=head1 LOGGING FUNCTIONS 123=head1 LOGGING FUNCTIONS
124 124
125These functions allow you to log messages. They always use the caller's 125The following functions allow you to log messages. They always use the
126package as a "logging context". Also, the main logging function C<log> is 126caller's package as a "logging context". Also, the main logging function,
127callable as C<AnyEvent::log> or C<AE::log> when the C<AnyEvent> module is 127C<log>, is aliased to C<AnyEvent::log> and C<AE::log> when the C<AnyEvent>
128loaded. 128module is loaded.
129 129
130=over 4 130=over 4
131 131
132=cut 132=cut
133 133
134package AnyEvent::Log; 134package AnyEvent::Log;
135 135
136use Carp (); 136use Carp ();
137use POSIX (); 137use POSIX ();
138
139# layout of a context
140# 0 1 2 3 4, 5
141# [$title, $level, %$slaves, &$logcb, &$fmtcb, $cap]
138 142
139use AnyEvent (); BEGIN { AnyEvent::common_sense } 143use AnyEvent (); BEGIN { AnyEvent::common_sense }
140#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
141 145
142our $VERSION = $AnyEvent::VERSION; 146our $VERSION = $AnyEvent::VERSION;
187 191
188Last 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
189supposed 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
190actually 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
191message 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.
192 199
193Whether 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
194and 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
195messages or not "lost" - for example, when L<AnyEvent::Debug> detects a 202messages or not "lost" - for example, when L<AnyEvent::Debug> detects a
196runtime 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
277 ? $level+0 284 ? $level+0
278 : $STR2LEVEL{$level} || Carp::croak "$level: not a valid logging level, caught"; 285 : $STR2LEVEL{$level} || Carp::croak "$level: not a valid logging level, caught";
279 286
280 my $mask = 1 << $level; 287 my $mask = 1 << $level;
281 288
282 my ($success, %seen, @ctx, $now, $fmt); 289 my ($success, %seen, @ctx, $now, @fmt);
283 290
284 do 291 do
285 { 292 {
286 # skip if masked 293 # if !ref, then it's a level number
294 if (!ref $ctx) {
295 $level = $ctx;
287 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
288 if ($ctx->[3]) { 306 if ($ctx->[3]) {
289 # logging target found 307 # logging target found
308
309 local ($!, $@);
290 310
291 # now get raw message, unless we have it already 311 # now get raw message, unless we have it already
292 unless ($now) { 312 unless ($now) {
293 $format = $format->() if ref $format; 313 $format = $format->() if ref $format;
294 $format = sprintf $format, @args if @args; 314 $format = sprintf $format, @args if @args;
297 }; 317 };
298 318
299 # format msg 319 # format msg
300 my $str = $ctx->[4] 320 my $str = $ctx->[4]
301 ? $ctx->[4]($now, $_[0], $level, $format) 321 ? $ctx->[4]($now, $_[0], $level, $format)
302 : ($fmt ||= _format $now, $_[0], $level, $format); 322 : ($fmt[$level] ||= _format $now, $_[0], $level, $format);
303 323
304 $success = 1; 324 $success = 1;
305 325
306 $ctx->[3]($str) 326 $ctx->[3]($str)
307 or push @ctx, values %{ $ctx->[2] }; # not consumed - propagate 327 or push @ctx, values %{ $ctx->[2] }; # not consumed - propagate
611package AnyEvent::Log::COLLECT; 631package AnyEvent::Log::COLLECT;
612package AE::Log::COLLECT; 632package AE::Log::COLLECT;
613 633
614package AnyEvent::Log::Ctx; 634package AnyEvent::Log::Ctx;
615 635
616# 0 1 2 3 4
617# [$title, $level, %$slaves, &$logcb, &$fmtcb]
618
619=item $ctx = new AnyEvent::Log::Ctx methodname => param... 636=item $ctx = new AnyEvent::Log::Ctx methodname => param...
620 637
621This is a convenience constructor that makes it simpler to construct 638This is a convenience constructor that makes it simpler to construct
622anonymous logging contexts. 639anonymous logging contexts.
623 640
710 727
711=item $ctx->disable ($level[, $level...]) 728=item $ctx->disable ($level[, $level...])
712 729
713Disables logging for the given levels, leaving all others unchanged. 730Disables logging for the given levels, leaving all others unchanged.
714 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
715=cut 754=cut
716 755
717sub _lvl_lst { 756sub _lvl_lst {
718 map { 757 map {
719 $_ > 0 && $_ <= 9 ? $_+0 758 $_ > 0 && $_ <= 9 ? $_+0
720 : $_ eq "all" ? (1 .. 9) 759 : $_ eq "all" ? (1 .. 9)
721 : $STR2LEVEL{$_} || Carp::croak "$_: not a valid logging level, caught" 760 : $STR2LEVEL{$_} || Carp::croak "$_: not a valid logging level, caught"
722 } @_ 761 } @_
723} 762}
724 763
764sub _lvl {
765 $_[0] =~ /^(?:0|off|none)$/ ? 0 : (_lvl_lst $_[0])[-1]
766}
767
725our $NOP_CB = sub { 0 }; 768our $NOP_CB = sub { 0 };
726 769
727sub levels { 770sub levels {
728 my $ctx = shift; 771 my $ctx = shift;
729 $ctx->[1] = 0; 772 $ctx->[1] = 0;
732 AnyEvent::Log::_reassess; 775 AnyEvent::Log::_reassess;
733} 776}
734 777
735sub level { 778sub level {
736 my $ctx = shift; 779 my $ctx = shift;
737 my $lvl = $_[0] =~ /^(?:0|off|none)$/ ? 0 : (_lvl_lst $_[0])[-1];
738
739 $ctx->[1] = ((1 << $lvl) - 1) << 1; 780 $ctx->[1] = ((1 << &_lvl) - 1) << 1;
740 AnyEvent::Log::_reassess; 781 AnyEvent::Log::_reassess;
741} 782}
742 783
743sub enable { 784sub enable {
744 my $ctx = shift; 785 my $ctx = shift;
752 $ctx->[1] &= ~(1 << $_) 793 $ctx->[1] &= ~(1 << $_)
753 for &_lvl_lst; 794 for &_lvl_lst;
754 AnyEvent::Log::_reassess; 795 AnyEvent::Log::_reassess;
755} 796}
756 797
798sub cap {
799 my $ctx = shift;
800 $ctx->[5] = &_lvl;
801}
802
757=back 803=back
758 804
759=head3 SLAVE CONTEXTS 805=head3 SLAVE CONTEXTS
760 806
761The following methods attach and detach another logging context to a 807The following methods attach and detach another logging context to a
853logging context, the (numeric) logging level and the raw message string 899logging context, the (numeric) logging level and the raw message string
854and needs to return a formatted log message. In most cases this will be a 900and needs to return a formatted log message. In most cases this will be a
855string, but it could just as well be an array reference that just stores 901string, but it could just as well be an array reference that just stores
856the values. 902the values.
857 903
858If, for some reason, you want to use C<caller> to find out more baout the 904If, for some reason, you want to use C<caller> to find out more about the
859logger then you should walk up the call stack until you are no longer 905logger then you should walk up the call stack until you are no longer
860inside the C<AnyEvent::Log> package. 906inside the C<AnyEvent::Log> package.
861 907
862Example: format just the raw message, with numeric log level in angle 908Example: format just the raw message, with numeric log level in angle
863brackets. 909brackets.
1091=item C<nolog> 1137=item C<nolog>
1092 1138
1093Configures the context to not log anything by itself, which is the 1139Configures the context to not log anything by itself, which is the
1094default. Same as C<< $ctx->log_cb (undef) >>. 1140default. Same as C<< $ctx->log_cb (undef) >>.
1095 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
1096=item C<0> or C<off> 1148=item C<0> or C<off>
1097 1149
1098Sets 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
1099filtered out. 1151filtered out.
1100 1152
1101=item C<all> 1153=item C<all>
1102 1154
1103Enables all logging levels, i.e. filtering will effectively be switched 1155Enables all logging levels, i.e. filtering will effectively be switched
1145 1197
1146Attaches the named context as slave to the context. 1198Attaches the named context as slave to the context.
1147 1199
1148=item C<+> 1200=item C<+>
1149 1201
1150A 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
1151context. Anonymous (C<%name>) contexts have no attached slaves by default, 1203context. Anonymous (C<%name>) contexts have no attached slaves by default,
1152but package contexts have the parent context as slave by default. 1204but package contexts have the parent context as slave by default.
1153 1205
1154Example: 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
1155default log collector. 1207default log collector.
1186 1238
1187 my $pkg = sub { 1239 my $pkg = sub {
1188 $_[0] eq "log" ? $LOG 1240 $_[0] eq "log" ? $LOG
1189 : $_[0] eq "filter" ? $FILTER 1241 : $_[0] eq "filter" ? $FILTER
1190 : $_[0] eq "collect" ? $COLLECT 1242 : $_[0] eq "collect" ? $COLLECT
1191 : $_[0] =~ /^%(.+)$/ ? ($anon{$1} ||= ctx undef) 1243 : $_[0] =~ /^%(.+)$/ ? ($anon{$1} ||= do { my $ctx = ctx undef; $ctx->[0] = $_[0]; $ctx })
1192 : $_[0] =~ /^(.*?)(?:::)?$/ ? ctx "$1" # egad :/ 1244 : $_[0] =~ /^(.*?)(?:::)?$/ ? ctx "$1" # egad :/
1193 : die # never reached? 1245 : die # never reached?
1194 }; 1246 };
1195 1247
1196 /\G[[:space:]]+/gc; # skip initial whitespace 1248 /\G[[:space:]]+/gc; # skip initial whitespace
1202 while (/\G((?:[^,:[:space:]]+|::|\\.)+)/gc) { 1254 while (/\G((?:[^,:[:space:]]+|::|\\.)+)/gc) {
1203 for ("$1") { 1255 for ("$1") {
1204 if ($_ eq "stderr" ) { $ctx->log_to_warn; 1256 if ($_ eq "stderr" ) { $ctx->log_to_warn;
1205 } elsif (/^file=(.+)/ ) { $ctx->log_to_file ("$1"); 1257 } elsif (/^file=(.+)/ ) { $ctx->log_to_file ("$1");
1206 } elsif (/^path=(.+)/ ) { $ctx->log_to_path ("$1"); 1258 } elsif (/^path=(.+)/ ) { $ctx->log_to_path ("$1");
1207 } elsif (/syslog(?:=(.*))?/ ) { require Sys::Syslog; $ctx->log_to_syslog ($1); 1259 } elsif (/^syslog(?:=(.*))?/ ) { require Sys::Syslog; $ctx->log_to_syslog ("$1");
1208 } elsif ($_ eq "nolog" ) { $ctx->log_cb (undef); 1260 } elsif ($_ eq "nolog" ) { $ctx->log_cb (undef);
1261 } elsif (/^cap=(.+)/ ) { $ctx->cap ("$1");
1209 } elsif (/^\+(.+)$/ ) { $ctx->attach ($pkg->("$1")); 1262 } elsif (/^\+(.+)$/ ) { $ctx->attach ($pkg->("$1"));
1210 } elsif ($_ eq "+" ) { $ctx->slaves; 1263 } elsif ($_ eq "+" ) { $ctx->slaves;
1211 } elsif ($_ eq "off" or $_ eq "0") { $ctx->level (0); 1264 } elsif ($_ eq "off" or $_ eq "0") { $ctx->level (0);
1212 } elsif ($_ eq "all" ) { $ctx->level ("all"); 1265 } elsif ($_ eq "all" ) { $ctx->level ("all");
1213 } elsif ($_ eq "level" ) { $ctx->level ("all"); $level = "level"; 1266 } elsif ($_ eq "level" ) { $ctx->level ("all"); $level = "level";
1281 1334
1282 PERL_ANYEVENT_LOG=%filelogger=file=/some/path:collect=+%filelogger 1335 PERL_ANYEVENT_LOG=%filelogger=file=/some/path:collect=+%filelogger
1283 1336
1284In both cases, messages are still written to STDERR. 1337In both cases, messages are still written to STDERR.
1285 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
1286=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).
1287 1357
1288Attach the C<$AnyEvent::Log::LOG> context to the C<AnyEvent::Debug> 1358Attach the C<$AnyEvent::Log::LOG> context to the C<AnyEvent::Debug>
1289context - this simply circumvents the global filtering for trace messages. 1359context - this simply circumvents the global filtering for trace messages.
1290 1360

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines