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.48 by root, Thu Mar 22 00:19:39 2012 UTC vs.
Revision 1.67 by root, Sun May 12 10:32:26 2019 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 temperature is too hot!";
14 AE::log error => "Division by zero attempted.";
15 AE::log warn => "Couldn't delete the file.";
16 AE::log note => "Wanted 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 documented them.
122 136
123=head1 LOGGING FUNCTIONS 137=head1 LOGGING FUNCTIONS
124 138
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
859the logging (which consists of formatting the message and printing it or 908the logging (which consists of formatting the message and printing it or
860whatever it wants to do with it). 909whatever it wants to do with it).
861 910
862=over 4 911=over 4
863 912
864=item $ctx->log_cb ($cb->($str) 913=item $ctx->log_cb ($cb->($str))
865 914
866Replaces the logging callback on the context (C<undef> disables the 915Replaces the logging callback on the context (C<undef> disables the
867logging callback). 916logging callback).
868 917
869The logging callback is responsible for handling formatted log messages 918The logging callback is responsible for handling formatted log messages
894 943
895Replaces the formatting callback on the context (C<undef> restores the 944Replaces the formatting callback on the context (C<undef> restores the
896default formatter). 945default formatter).
897 946
898The callback is passed the (possibly fractional) timestamp, the original 947The callback is passed the (possibly fractional) timestamp, the original
899logging context, the (numeric) logging level and the raw message string 948logging context (object, not title), the (numeric) logging level and
900and needs to return a formatted log message. In most cases this will be a 949the 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 950most cases this will be a string, but it could just as well be an array
902the values. 951reference that just stores the values.
903 952
904If, for some reason, you want to use C<caller> to find out more baout the 953If, 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 954logger then you should walk up the call stack until you are no longer
906inside the C<AnyEvent::Log> package. 955inside the C<AnyEvent::Log> package.
907 956
957To implement your own logging callback, you might find the
958C<AnyEvent::Log::format_time> and C<AnyEvent::Log::default_format>
959functions useful.
960
961Example: format the message just as AnyEvent::Log would, by letting
962AnyEvent::Log do the work. This is a good basis to design a formatting
963callback that only changes minor aspects of the formatting.
964
965 $ctx->fmt_cb (sub {
966 my ($time, $ctx, $lvl, $msg) = @_;
967
968 AnyEvent::Log::default_format $time, $ctx, $lvl, $msg
969 });
970
908Example: format just the raw message, with numeric log level in angle 971Example: format just the raw message, with numeric log level in angle
909brackets. 972brackets.
910 973
911 $ctx->fmt_cb (sub { 974 $ctx->fmt_cb (sub {
912 my ($time, $ctx, $lvl, $msg) = @_; 975 my ($time, $ctx, $lvl, $msg) = @_;
913 976
914 "<$lvl>$msg\n" 977 "<$lvl>$msg\n"
915 }); 978 });
916 979
917Example: return an array reference with just the log values, and use 980Example: return an array reference with just the log values, and use
918C<PApp::SQL::sql_exec> to store the emssage in a database. 981C<PApp::SQL::sql_exec> to store the message in a database.
919 982
920 $ctx->fmt_cb (sub { \@_ }); 983 $ctx->fmt_cb (sub { \@_ });
921 $ctx->log_cb (sub { 984 $ctx->log_cb (sub {
922 my ($msg) = @_; 985 my ($msg) = @_;
923 986
935Sets the C<log_cb> to simply use C<CORE::warn> to report any messages 998Sets the C<log_cb> to simply use C<CORE::warn> to report any messages
936(usually this logs to STDERR). 999(usually this logs to STDERR).
937 1000
938=item $ctx->log_to_file ($path) 1001=item $ctx->log_to_file ($path)
939 1002
940Sets the C<log_cb> to log to a file (by appending), unbuffered. 1003Sets the C<log_cb> to log to a file (by appending), unbuffered. The
1004function might return before the log file has been opened or created.
941 1005
942=item $ctx->log_to_path ($path) 1006=item $ctx->log_to_path ($path)
943 1007
944Same as C<< ->log_to_file >>, but opens the file for each message. This 1008Same 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 1009is much slower, but allows you to change/move/rename/delete the file at
980 warn shift; 1044 warn shift;
981 0 1045 0
982 }); 1046 });
983} 1047}
984 1048
1049# this function is a good example of why threads are a must,
1050# simply for priority inversion.
1051sub _log_to_disk {
1052 # eval'uating this at runtime saves 220kb rss - perl has become
1053 # an insane memory waster.
1054 eval q{ # poor man's autoloading {}
1055 sub _log_to_disk {
1056 my ($ctx, $path, $keepopen) = @_;
1057
1058 my $fh;
1059 my @queue;
1060 my $delay;
1061 my $disable;
1062
1063 use AnyEvent::IO ();
1064
1065 my $kick = sub {
1066 undef $delay;
1067 return unless @queue;
1068 $delay = 1;
1069
1070 # we pass $kick to $kick, so $kick itself doesn't keep a reference to $kick.
1071 my $kick = shift;
1072
1073 # write one or more messages
1074 my $write = sub {
1075 # we write as many messages as have been queued
1076 my $data = join "", @queue;
1077 @queue = ();
1078
1079 AnyEvent::IO::aio_write $fh, $data, sub {
1080 $disable = 1;
1081 @_
1082 ? ($_[0] == length $data or AE::log 4 => "unable to write to logfile '$path': short write")
1083 : AE::log 4 => "unable to write to logfile '$path': $!";
1084 undef $disable;
1085
1086 if ($keepopen) {
1087 $kick->($kick);
1088 } else {
1089 AnyEvent::IO::aio_close ($fh, sub {
1090 undef $fh;
1091 $kick->($kick);
1092 });
1093 }
1094 };
1095 };
1096
1097 if ($fh) {
1098 $write->();
1099 } else {
1100 AnyEvent::IO::aio_open
1101 $path,
1102 AnyEvent::IO::O_CREAT | AnyEvent::IO::O_WRONLY | AnyEvent::IO::O_APPEND,
1103 0666,
1104 sub {
1105 $fh = shift
1106 or do {
1107 $disable = 1;
1108 AE::log 4 => "unable to open logfile '$path': $!";
1109 undef $disable;
1110 return;
1111 };
1112
1113 $write->();
1114 }
1115 ;
1116 }
1117 };
1118
1119 $ctx->log_cb (sub {
1120 return if $disable;
1121 push @queue, shift;
1122 $kick->($kick) unless $delay;
1123 0
1124 });
1125
1126 $kick->($kick) if $keepopen; # initial open
1127 };
1128 };
1129 die if $@;
1130 &_log_to_disk
1131}
1132
985sub log_to_file { 1133sub log_to_file {
986 my ($ctx, $path) = @_; 1134 my ($ctx, $path) = @_;
987 1135
988 open my $fh, ">>", $path 1136 _log_to_disk $ctx, $path, 1;
989 or die "$path: $!";
990
991 $ctx->log_cb (sub {
992 syswrite $fh, shift;
993 0
994 });
995} 1137}
996 1138
997sub log_to_path { 1139sub log_to_path {
998 my ($ctx, $path) = @_; 1140 my ($ctx, $path) = @_;
999 1141
1000 $ctx->log_cb (sub { 1142 _log_to_disk $ctx, $path, 0;
1001 open my $fh, ">>", $path
1002 or die "$path: $!";
1003
1004 syswrite $fh, shift;
1005 0
1006 });
1007} 1143}
1008 1144
1009sub log_to_syslog { 1145sub log_to_syslog {
1010 my ($ctx, $facility) = @_; 1146 my ($ctx, $facility) = @_;
1011 1147
1040=over 4 1176=over 4
1041 1177
1042=item $ctx->log ($level, $msg[, @params]) 1178=item $ctx->log ($level, $msg[, @params])
1043 1179
1044Same as C<AnyEvent::Log::log>, but uses the given context as log context. 1180Same as C<AnyEvent::Log::log>, but uses the given context as log context.
1181
1182Example: log a message in the context of another package.
1183
1184 (AnyEvent::Log::ctx "Other::Package")->log (warn => "heely bo");
1045 1185
1046=item $logger = $ctx->logger ($level[, \$enabled]) 1186=item $logger = $ctx->logger ($level[, \$enabled])
1047 1187
1048Same as C<AnyEvent::Log::logger>, but uses the given context as log 1188Same as C<AnyEvent::Log::logger>, but uses the given context as log
1049context. 1189context.
1096=item C<%name> 1236=item C<%name>
1097 1237
1098Context names starting with a C<%> are anonymous contexts created when the 1238Context names starting with a C<%> are anonymous contexts created when the
1099name is first mentioned. The difference to package contexts is that by 1239name is first mentioned. The difference to package contexts is that by
1100default they have no attached slaves. 1240default they have no attached slaves.
1241
1242This makes it possible to create new log contexts that can be refered to
1243multiple times by name within the same log specification.
1101 1244
1102=item a perl package name 1245=item a perl package name
1103 1246
1104Any other string references the logging context associated with the given 1247Any other string references the logging context associated with the given
1105Perl C<package>. In the unlikely case where you want to specify a package 1248Perl C<package>. In the unlikely case where you want to specify a package
1283 if (/\G(.+)/g) { 1426 if (/\G(.+)/g) {
1284 die "PERL_ANYEVENT_LOG ($spec): parse error at '$1'\n"; 1427 die "PERL_ANYEVENT_LOG ($spec): parse error at '$1'\n";
1285 } 1428 }
1286} 1429}
1287 1430
12881;
1289
1290=head1 EXAMPLES 1431=head1 EXAMPLES
1291 1432
1292This section shows some common configurations, both as code, and as 1433This section shows some common configurations, both as code, and as
1293C<PERL_ANYEVENT_LOG> string. 1434C<PERL_ANYEVENT_LOG> string.
1294 1435
1367assumes the log level for AnyEvent::Debug hasn't been changed from the 1508assumes the log level for AnyEvent::Debug hasn't been changed from the
1368default. 1509default.
1369 1510
1370=back 1511=back
1371 1512
1513=head1 ASYNCHRONOUS DISK I/O
1514
1515This module uses L<AnyEvent::IO> to actually write log messages (in
1516C<log_to_file> and C<log_to_path>), so it doesn't block your program when
1517the disk is busy and a non-blocking L<AnyEvent::IO> backend is available.
1518
1372=head1 AUTHOR 1519=head1 AUTHOR
1373 1520
1374 Marc Lehmann <schmorp@schmorp.de> 1521 Marc Lehmann <schmorp@schmorp.de>
1375 http://home.schmorp.de/ 1522 http://anyevent.schmorp.de
1376 1523
1377=cut 1524=cut
1378 1525
15261
1527

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines