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.49 by root, Thu Mar 22 01:03:57 2012 UTC vs.
Revision 1.71 by root, Mon Aug 3 20:53:18 2020 UTC

6 6
7Simple uses: 7Simple uses:
8 8
9 use AnyEvent; 9 use AnyEvent;
10 10
11 AE::log fatal => "No config found, cannot continue!"; # never returns
12 AE::log alert => "The battery died!";
13 AE::log crit => "The battery is too hot!";
14 AE::log error => "Division by zero attempted.";
15 AE::log warn => "Couldn't delete the file.";
16 AE::log note => "Attempted to create config, but config already exists.";
17 AE::log info => "File soandso successfully deleted.";
18 AE::log debug => "the function returned 3";
11 AE::log trace => "going to call function abc"; 19 AE::log trace => "going to call function abc";
12 AE::log debug => "the function returned 3";
13 AE::log info => "file soandso successfully deleted";
14 AE::log note => "wanted to create config, but config was already 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
20 20
21Log level overview: 21Log level overview:
22 22
23 LVL NAME SYSLOG PERL NOTE 23 LVL NAME SYSLOG PERL NOTE
24 1 fatal emerg exit system unusable, aborts program! 24 1 fatal emerg exit system unusable, aborts program!
33 33
34"Complex" uses (for speed sensitive code, e.g. trace/debug messages): 34"Complex" uses (for speed sensitive code, e.g. trace/debug messages):
35 35
36 use AnyEvent::Log; 36 use AnyEvent::Log;
37 37
38 my $tracer = AnyEvent::Log::logger trace => \$my $trace; 38 my $tracer = AnyEvent::Log::logger trace => \my $trace;
39 39
40 $tracer->("i am here") if $trace; 40 $tracer->("i am here") if $trace;
41 $tracer->(sub { "lots of data: " . Dumper $self }) if $trace; 41 $tracer->(sub { "lots of data: " . Dumper $self }) if $trace;
42 42
43Configuration (also look at the EXAMPLES section): 43Configuration (also look at the EXAMPLES section):
44 44
45 # set default logging level to suppress anything below "notice"
46 # i.e. enable logging at "notice" or above - the default is to
47 # to not log anything at all.
48 $AnyEvent::Log::FILTER->level ("notice");
49
45 # set logging for the current package to errors and higher only 50 # set logging for the current package to errors and higher only
46 AnyEvent::Log::ctx->level ("error"); 51 AnyEvent::Log::ctx->level ("error");
47 52
48 # set logging level to suppress anything below "notice" 53 # enable logging for the current package, regardless of global logging level
49 $AnyEvent::Log::FILTER->level ("notice"); 54 AnyEvent::Log::ctx->attach ($AnyEvent::Log::LOG);
55
56 # enable debug logging for module some::mod and enable logging by default
57 (AnyEvent::Log::ctx "some::mod")->level ("debug");
58 (AnyEvent::Log::ctx "some::mod")->attach ($AnyEvent::Log::LOG);
50 59
51 # send all critical and higher priority messages to syslog, 60 # send all critical and higher priority messages to syslog,
52 # regardless of (most) other settings 61 # regardless of (most) other settings
53 $AnyEvent::Log::COLLECT->attach (new AnyEvent::Log::Ctx 62 $AnyEvent::Log::COLLECT->attach (new AnyEvent::Log::Ctx
54 level => "critical", 63 level => "critical",
61attempt to be "the" logging solution or even "a" logging solution for 70attempt to be "the" logging solution or even "a" logging solution for
62AnyEvent - AnyEvent simply creates logging messages internally, and this 71AnyEvent - AnyEvent simply creates logging messages internally, and this
63module more or less exposes the mechanism, with some extra spiff to allow 72module more or less exposes the mechanism, with some extra spiff to allow
64using it from other modules as well. 73using it from other modules as well.
65 74
66Remember that the default verbosity level is C<3> (C<critical>), so little 75Remember that the default verbosity level is C<4> (C<error>), so only
67will be logged, unless you set C<PERL_ANYEVENT_VERBOSE> to a higher number 76errors and more important messages will be logged, unless you set
68before starting your program, or change the logging level at runtime with 77C<PERL_ANYEVENT_VERBOSE> to a higher number before starting your program
69something like: 78(C<AE_VERBOSE=5> is recommended during development), or change the logging
79level at runtime with something like:
70 80
71 use AnyEvent::Log; 81 use AnyEvent::Log;
72 $AnyEvent::Log::FILTER->level ("info"); 82 $AnyEvent::Log::FILTER->level ("info");
73 83
74The design goal behind this module was to keep it simple (and small), 84The 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 85but make it powerful enough to be potentially useful for any module,
76extensive enough for the most common tasks, such as logging to multiple 86and extensive enough for the most common tasks, such as logging to
77targets, or being able to log into a database. 87multiple targets, or being able to log into a database.
78 88
79The module is also usable before AnyEvent itself is initialised, in which 89The module is also usable before AnyEvent itself is initialised, in which
80case some of the functionality might be reduced. 90case some of the functionality might be reduced.
81 91
82The amount of documentation might indicate otherwise, but the runtime part 92The amount of documentation might indicate otherwise, but the runtime part
115 125
116You can normally only log a message once at highest priority level (C<1>, 126You can normally only log a message once at highest priority level (C<1>,
117C<fatal>), because logging a fatal message will also quit the program - so 127C<fatal>), because logging a fatal message will also quit the program - so
118use it sparingly :) 128use it sparingly :)
119 129
130For example, a program that finds an unknown switch on the commandline
131might well use a fatal logging level to tell users about it - the "system"
132in this case would be the program, or module.
133
120Some methods also offer some extra levels, such as C<0>, C<off>, C<none> 134Some methods also offer some extra levels, such as C<0>, C<off>, C<none>
121or C<all> - these are only valid for the methods that documented them. 135or C<all> - these are only valid for the methods that document them.
122 136
123=head1 LOGGING FUNCTIONS 137=head1 LOGGING FUNCTIONS
124 138
125The following functions allow you to log messages. They always use the 139The following functions allow you to log messages. They always use the
126caller's package as a "logging context". Also, the main logging function, 140caller's package as a "logging context". Also, the main logging function,
148our ($COLLECT, $FILTER, $LOG); 162our ($COLLECT, $FILTER, $LOG);
149 163
150our ($now_int, $now_str1, $now_str2); 164our ($now_int, $now_str1, $now_str2);
151 165
152# Format Time, not public - yet? 166# Format Time, not public - yet?
153sub ft($) { 167sub format_time($) {
154 my $i = int $_[0]; 168 my $i = int $_[0];
155 my $f = sprintf "%06d", 1e6 * ($_[0] - $i); 169 my $f = sprintf "%06d", 1e6 * ($_[0] - $i);
156 170
157 ($now_int, $now_str1, $now_str2) = ($i, split /\x01/, POSIX::strftime "%Y-%m-%d %H:%M:%S.\x01 %z", localtime $i) 171 ($now_int, $now_str1, $now_str2) = ($i, split /\x01/, POSIX::strftime "%Y-%m-%d %H:%M:%S.\x01 %z", localtime $i)
158 if $now_int != $i; 172 if $now_int != $i;
257}; 271};
258 272
259our @LEVEL2STR = qw(0 fatal alert crit error warn note info debug trace); 273our @LEVEL2STR = qw(0 fatal alert crit error warn note info debug trace);
260 274
261# time, ctx, level, msg 275# time, ctx, level, msg
262sub _format($$$$) { 276sub default_format($$$$) {
263 my $ts = ft $_[0]; 277 my $ts = format_time $_[0];
264 my $ct = " "; 278 my $ct = " ";
265 279
266 my @res; 280 my @res;
267 281
268 for (split /\n/, sprintf "%-5s %s: %s", $LEVEL2STR[$_[2]], $_[1][0], $_[3]) { 282 for (split /\n/, sprintf "%-5s %s: %s", $LEVEL2STR[$_[2]], $_[1][0], $_[3]) {
317 }; 331 };
318 332
319 # format msg 333 # format msg
320 my $str = $ctx->[4] 334 my $str = $ctx->[4]
321 ? $ctx->[4]($now, $_[0], $level, $format) 335 ? $ctx->[4]($now, $_[0], $level, $format)
322 : ($fmt[$level] ||= _format $now, $_[0], $level, $format); 336 : ($fmt[$level] ||= default_format $now, $_[0], $level, $format);
323 337
324 $success = 1; 338 $success = 1;
325 339
326 $ctx->[3]($str) 340 $ctx->[3]($str)
327 or push @ctx, values %{ $ctx->[2] }; # not consumed - propagate 341 or push @ctx, values %{ $ctx->[2] }; # not consumed - propagate
449Since C<AnyEvent::Log> has to work even before the L<AnyEvent> has been 463Since C<AnyEvent::Log> has to work even before the L<AnyEvent> has been
450initialised, this switch will also decide whether to use C<CORE::time> or 464initialised, this switch will also decide whether to use C<CORE::time> or
451C<Time::HiRes::time> when logging a message before L<AnyEvent> becomes 465C<Time::HiRes::time> when logging a message before L<AnyEvent> becomes
452available. 466available.
453 467
468=item AnyEvent::Log::format_time $timestamp
469
470Formats a timestamp as returned by C<< AnyEvent->now >> or C<<
471AnyEvent->time >> or many other functions in the same way as
472C<AnyEvent::Log> does.
473
474In your main program (as opposed to in your module) you can override
475the default timestamp display format by loading this module and then
476redefining this function.
477
478Most commonly, this function can be used in formatting callbacks.
479
480=item AnyEvent::Log::default_format $time, $ctx, $level, $msg
481
482Format a log message using the given timestamp, logging context, log level
483and log message.
484
485This is the formatting function used to format messages when no custom
486function is provided.
487
488In your main program (as opposed to in your module) you can override the
489default message format by loading this module and then redefining this
490function.
491
492=item AnyEvent::Log::fatal_exit()
493
494This is the function that is called after logging a C<fatal> log
495message. It must not return.
496
497The default implementation simply calls C<exit 1>.
498
499In your main program (as opposed to in your module) you can override
500the fatal exit function by loading this module and then redefining this
501function. Make sure you don't return.
502
454=back 503=back
455 504
456=head1 LOGGING CONTEXTS 505=head1 LOGGING CONTEXTS
457 506
458This module associates every log message with a so-called I<logging 507This module associates every log message with a so-called I<logging
545 594
546=item $ctx = AnyEvent::Log::ctx [$pkg] 595=item $ctx = AnyEvent::Log::ctx [$pkg]
547 596
548This function creates or returns a logging context (which is an object). 597This function creates or returns a logging context (which is an object).
549 598
550If a package name is given, then the context for that packlage is 599If a package name is given, then the context for that package is
551returned. If it is called without any arguments, then the context for the 600returned. If it is called without any arguments, then the context for the
552callers package is returned (i.e. the same context as a C<AE::log> call 601callers package is returned (i.e. the same context as a C<AE::log> call
553would use). 602would use).
554 603
555If C<undef> is given, then it creates a new anonymous context that is not 604If C<undef> is given, then it creates a new anonymous context that is not
835sub attach { 884sub attach {
836 my $ctx = shift; 885 my $ctx = shift;
837 886
838 $ctx->[2]{$_+0} = $_ 887 $ctx->[2]{$_+0} = $_
839 for map { AnyEvent::Log::ctx $_ } @_; 888 for map { AnyEvent::Log::ctx $_ } @_;
889 AnyEvent::Log::_reassess;
840} 890}
841 891
842sub detach { 892sub detach {
843 my $ctx = shift; 893 my $ctx = shift;
844 894
845 delete $ctx->[2]{$_+0} 895 delete $ctx->[2]{$_+0}
846 for map { AnyEvent::Log::ctx $_ } @_; 896 for map { AnyEvent::Log::ctx $_ } @_;
897 AnyEvent::Log::_reassess;
847} 898}
848 899
849sub slaves { 900sub slaves {
850 undef $_[0][2]; 901 undef $_[0][2];
851 &attach; 902 &attach;
903 AnyEvent::Log::_reassess;
852} 904}
853 905
854=back 906=back
855 907
856=head3 LOG TARGETS 908=head3 LOG TARGETS
859the logging (which consists of formatting the message and printing it or 911the logging (which consists of formatting the message and printing it or
860whatever it wants to do with it). 912whatever it wants to do with it).
861 913
862=over 4 914=over 4
863 915
864=item $ctx->log_cb ($cb->($str) 916=item $ctx->log_cb ($cb->($str))
865 917
866Replaces the logging callback on the context (C<undef> disables the 918Replaces the logging callback on the context (C<undef> disables the
867logging callback). 919logging callback).
868 920
869The logging callback is responsible for handling formatted log messages 921The logging callback is responsible for handling formatted log messages
894 946
895Replaces the formatting callback on the context (C<undef> restores the 947Replaces the formatting callback on the context (C<undef> restores the
896default formatter). 948default formatter).
897 949
898The callback is passed the (possibly fractional) timestamp, the original 950The callback is passed the (possibly fractional) timestamp, the original
899logging context, the (numeric) logging level and the raw message string 951logging context (object, not title), the (numeric) logging level and
900and needs to return a formatted log message. In most cases this will be a 952the raw message string and needs to return a formatted log message. In
901string, but it could just as well be an array reference that just stores 953most cases this will be a string, but it could just as well be an array
902the values. 954reference that just stores the values.
903 955
904If, for some reason, you want to use C<caller> to find out more about the 956If, for some reason, you want to use C<caller> to find out more about the
905logger then you should walk up the call stack until you are no longer 957logger then you should walk up the call stack until you are no longer
906inside the C<AnyEvent::Log> package. 958inside the C<AnyEvent::Log> package.
907 959
960To implement your own logging callback, you might find the
961C<AnyEvent::Log::format_time> and C<AnyEvent::Log::default_format>
962functions useful.
963
964Example: format the message just as AnyEvent::Log would, by letting
965AnyEvent::Log do the work. This is a good basis to design a formatting
966callback that only changes minor aspects of the formatting.
967
968 $ctx->fmt_cb (sub {
969 my ($time, $ctx, $lvl, $msg) = @_;
970
971 AnyEvent::Log::default_format $time, $ctx, $lvl, $msg
972 });
973
908Example: format just the raw message, with numeric log level in angle 974Example: format just the raw message, with numeric log level in angle
909brackets. 975brackets.
910 976
911 $ctx->fmt_cb (sub { 977 $ctx->fmt_cb (sub {
912 my ($time, $ctx, $lvl, $msg) = @_; 978 my ($time, $ctx, $lvl, $msg) = @_;
913 979
914 "<$lvl>$msg\n" 980 "<$lvl>$msg\n"
915 }); 981 });
916 982
917Example: return an array reference with just the log values, and use 983Example: return an array reference with just the log values, and use
918C<PApp::SQL::sql_exec> to store the emssage in a database. 984C<PApp::SQL::sql_exec> to store the message in a database.
919 985
920 $ctx->fmt_cb (sub { \@_ }); 986 $ctx->fmt_cb (sub { \@_ });
921 $ctx->log_cb (sub { 987 $ctx->log_cb (sub {
922 my ($msg) = @_; 988 my ($msg) = @_;
923 989
935Sets the C<log_cb> to simply use C<CORE::warn> to report any messages 1001Sets the C<log_cb> to simply use C<CORE::warn> to report any messages
936(usually this logs to STDERR). 1002(usually this logs to STDERR).
937 1003
938=item $ctx->log_to_file ($path) 1004=item $ctx->log_to_file ($path)
939 1005
940Sets the C<log_cb> to log to a file (by appending), unbuffered. 1006Sets the C<log_cb> to log to a file (by appending), unbuffered. The
1007function might return before the log file has been opened or created.
941 1008
942=item $ctx->log_to_path ($path) 1009=item $ctx->log_to_path ($path)
943 1010
944Same as C<< ->log_to_file >>, but opens the file for each message. This 1011Same as C<< ->log_to_file >>, but opens the file for each message. This
945is much slower, but allows you to change/move/rename/delete the file at 1012is much slower, but allows you to change/move/rename/delete the file at
980 warn shift; 1047 warn shift;
981 0 1048 0
982 }); 1049 });
983} 1050}
984 1051
1052# this function is a good example of why threads are a must,
1053# simply for priority inversion.
1054sub _log_to_disk {
1055 # eval'uating this at runtime saves 220kb rss - perl has become
1056 # an insane memory waster.
1057 eval q{ # poor man's autoloading {}
1058 sub _log_to_disk {
1059 my ($ctx, $path, $keepopen) = @_;
1060
1061 my $fh;
1062 my @queue;
1063 my $delay;
1064 my $disable;
1065
1066 use AnyEvent::IO ();
1067
1068 my $kick = sub {
1069 undef $delay;
1070 return unless @queue;
1071 $delay = 1;
1072
1073 # we pass $kick to $kick, so $kick itself doesn't keep a reference to $kick.
1074 my $kick = shift;
1075
1076 # write one or more messages
1077 my $write = sub {
1078 # we write as many messages as have been queued
1079 my $data = join "", @queue;
1080 @queue = ();
1081
1082 AnyEvent::IO::aio_write $fh, $data, sub {
1083 $disable = 1;
1084 @_
1085 ? ($_[0] == length $data or AE::log 4 => "unable to write to logfile '$path': short write")
1086 : AE::log 4 => "unable to write to logfile '$path': $!";
1087 undef $disable;
1088
1089 if ($keepopen) {
1090 $kick->($kick);
1091 } else {
1092 AnyEvent::IO::aio_close ($fh, sub {
1093 undef $fh;
1094 $kick->($kick);
1095 });
1096 }
1097 };
1098 };
1099
1100 if ($fh) {
1101 $write->();
1102 } else {
1103 AnyEvent::IO::aio_open
1104 $path,
1105 AnyEvent::IO::O_CREAT | AnyEvent::IO::O_WRONLY | AnyEvent::IO::O_APPEND,
1106 0666,
1107 sub {
1108 $fh = shift
1109 or do {
1110 $disable = 1;
1111 AE::log 4 => "unable to open logfile '$path': $!";
1112 undef $disable;
1113 return;
1114 };
1115
1116 $write->();
1117 }
1118 ;
1119 }
1120 };
1121
1122 $ctx->log_cb (sub {
1123 return if $disable;
1124 push @queue, shift;
1125 $kick->($kick) unless $delay;
1126 0
1127 });
1128
1129 $kick->($kick) if $keepopen; # initial open
1130 };
1131 };
1132 die if $@;
1133 &_log_to_disk
1134}
1135
985sub log_to_file { 1136sub log_to_file {
986 my ($ctx, $path) = @_; 1137 my ($ctx, $path) = @_;
987 1138
988 open my $fh, ">>", $path 1139 _log_to_disk $ctx, $path, 1;
989 or die "$path: $!";
990
991 $ctx->log_cb (sub {
992 syswrite $fh, shift;
993 0
994 });
995} 1140}
996 1141
997sub log_to_path { 1142sub log_to_path {
998 my ($ctx, $path) = @_; 1143 my ($ctx, $path) = @_;
999 1144
1000 $ctx->log_cb (sub { 1145 _log_to_disk $ctx, $path, 0;
1001 open my $fh, ">>", $path
1002 or die "$path: $!";
1003
1004 syswrite $fh, shift;
1005 0
1006 });
1007} 1146}
1008 1147
1009sub log_to_syslog { 1148sub log_to_syslog {
1010 my ($ctx, $facility) = @_; 1149 my ($ctx, $facility) = @_;
1011 1150
1040=over 4 1179=over 4
1041 1180
1042=item $ctx->log ($level, $msg[, @params]) 1181=item $ctx->log ($level, $msg[, @params])
1043 1182
1044Same as C<AnyEvent::Log::log>, but uses the given context as log context. 1183Same as C<AnyEvent::Log::log>, but uses the given context as log context.
1184
1185Example: log a message in the context of another package.
1186
1187 (AnyEvent::Log::ctx "Other::Package")->log (warn => "heely bo");
1045 1188
1046=item $logger = $ctx->logger ($level[, \$enabled]) 1189=item $logger = $ctx->logger ($level[, \$enabled])
1047 1190
1048Same as C<AnyEvent::Log::logger>, but uses the given context as log 1191Same as C<AnyEvent::Log::logger>, but uses the given context as log
1049context. 1192context.
1096=item C<%name> 1239=item C<%name>
1097 1240
1098Context names starting with a C<%> are anonymous contexts created when the 1241Context names starting with a C<%> are anonymous contexts created when the
1099name is first mentioned. The difference to package contexts is that by 1242name is first mentioned. The difference to package contexts is that by
1100default they have no attached slaves. 1243default they have no attached slaves.
1244
1245This makes it possible to create new log contexts that can be refered to
1246multiple times by name within the same log specification.
1101 1247
1102=item a perl package name 1248=item a perl package name
1103 1249
1104Any other string references the logging context associated with the given 1250Any other string references the logging context associated with the given
1105Perl C<package>. In the unlikely case where you want to specify a package 1251Perl C<package>. In the unlikely case where you want to specify a package
1283 if (/\G(.+)/g) { 1429 if (/\G(.+)/g) {
1284 die "PERL_ANYEVENT_LOG ($spec): parse error at '$1'\n"; 1430 die "PERL_ANYEVENT_LOG ($spec): parse error at '$1'\n";
1285 } 1431 }
1286} 1432}
1287 1433
12881;
1289
1290=head1 EXAMPLES 1434=head1 EXAMPLES
1291 1435
1292This section shows some common configurations, both as code, and as 1436This section shows some common configurations, both as code, and as
1293C<PERL_ANYEVENT_LOG> string. 1437C<PERL_ANYEVENT_LOG> string.
1294 1438
1367assumes the log level for AnyEvent::Debug hasn't been changed from the 1511assumes the log level for AnyEvent::Debug hasn't been changed from the
1368default. 1512default.
1369 1513
1370=back 1514=back
1371 1515
1516=head1 ASYNCHRONOUS DISK I/O
1517
1518This module uses L<AnyEvent::IO> to actually write log messages (in
1519C<log_to_file> and C<log_to_path>), so it doesn't block your program when
1520the disk is busy and a non-blocking L<AnyEvent::IO> backend is available.
1521
1372=head1 AUTHOR 1522=head1 AUTHOR
1373 1523
1374 Marc Lehmann <schmorp@schmorp.de> 1524 Marc Lehmann <schmorp@schmorp.de>
1375 http://home.schmorp.de/ 1525 http://anyevent.schmorp.de
1376 1526
1377=cut 1527=cut
1378 1528
15291
1530

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines