]> git.donarmstrong.com Git - infobot.git/blob - src/logger.pl
75ebebc448075e77d788d6786aecf94fef1c3f4e
[infobot.git] / src / logger.pl
1 #
2 # logger.pl: logger functions!
3 #    Author: dms
4 #   Version: v0.4 (20000923)
5 #  FVersion: 19991205
6 #      NOTE: Based on code by Kevin Lenzo & Patrick Cole  (c) 1997
7 #
8
9 use strict;
10 use utf8;
11
12 use vars qw($statcount $bot_pid $forkedtime $statcountfix $addressed);
13 use vars qw($logDate $logold $logcount $logtime $logrepeat $running);
14 use vars qw(@backlog);
15 use vars qw(%param %file %cache);
16
17 $logtime   = time();
18 $logcount  = 0;
19 $logrepeat = 0;
20 $logold    = '';
21
22 $param{VEBOSITY} ||= 1;    # lame fix for preload
23
24 my %attributes = (
25     'clear'      => 0,
26     'reset'      => 0,
27     'bold'       => 1,
28     'underline'  => 4,
29     'underscore' => 4,
30     'blink'      => 5,
31     'reverse'    => 7,
32     'concealed'  => 8,
33     'black'      => 30,
34     'on_black'   => 40,
35     'red'        => 31,
36     'on_red'     => 41,
37     'green'      => 32,
38     'on_green'   => 42,
39     'yellow'     => 33,
40     'on_yellow'  => 43,
41     'blue'       => 34,
42     'on_blue'    => 44,
43     'magenta'    => 35,
44     'on_magenta' => 45,
45     'cyan'       => 36,
46     'on_cyan'    => 46,
47     'white'      => 37,
48     'on_white'   => 47
49 );
50
51 use vars qw($b_black $_black $b_red $_red $b_green $_green
52   $b_yellow $_yellow $b_blue $_blue $b_magenta $_magenta
53   $b_cyan $_cyan $b_white $_white $_reset $_bold $ob $b);
54
55 $b_black   = cl('bold black');
56 $_black    = cl('black');
57 $b_red     = cl('bold red');
58 $_red      = cl('red');
59 $b_green   = cl('bold green');
60 $_green    = cl('green');
61 $b_yellow  = cl('bold yellow');
62 $_yellow   = cl('yellow');
63 $b_blue    = cl('bold blue');
64 $_blue     = cl('blue');
65 $b_magenta = cl('bold magenta');
66 $_magenta  = cl('magenta');
67 $b_cyan    = cl('bold cyan');
68 $_cyan     = cl('cyan');
69 $b_white   = cl('bold white');
70 $_white    = cl('white');
71 $_reset    = cl('reset');
72 $_bold     = cl('bold');
73 $ob        = cl('reset');
74 $b         = cl('bold');
75
76 ############################################################################
77 # Implementation (attribute string form)
78 ############################################################################
79
80 # Return the escape code for a given set of color attributes.
81 sub cl {
82     my @codes = map { split } @_;
83     my $attribute = '';
84     foreach (@codes) {
85         $_ = lc $_;
86         unless ( defined $attributes{$_} ) { die "Invalid attribute name $_" }
87         $attribute .= $attributes{$_} . ';';
88     }
89     chop $attribute;
90     ( $attribute ne '' ) ? "\e[${attribute}m" : undef;
91 }
92
93 # logging support.
94 sub openLog {
95     binmode( STDOUT, ':encoding(UTF-8)' );
96     return unless ( &IsParam('logfile') );
97     $file{log} = $param{'logfile'};
98
99     my $error = 0;
100     my $path  = &getPath( $file{log} );
101     while ( !-d $path ) {
102         if ($error) {
103             &ERROR("openLog: failed opening log to $file{log}; disabling.");
104             delete $param{'logfile'};
105             return;
106         }
107
108         &status("openLog: making $path.");
109         last if ( mkdir $path, 0755 );
110         $error++;
111     }
112
113     if ( &IsParam('logType') and $param{'logType'} =~ /DAILY/i ) {
114         my ( $day, $month, $year ) = ( gmtime time() )[ 3, 4, 5 ];
115         $logDate = sprintf( '%04d%02d%02d', $year + 1900, $month + 1, $day );
116         $file{log} .= $logDate;
117     }
118
119     if ( open( LOG, ">>$file{log}" ) ) {
120         binmode( LOG, ':encoding(UTF-8)' );
121         &status("Opened logfile $file{log}.");
122         LOG->autoflush(1);
123     }
124     else {
125         &status("Cannot open logfile ($file{log}); not logging: $!");
126     }
127 }
128
129 sub closeLog {
130
131     # lame fix for paramlogfile.
132     return unless ( &IsParam('logfile') );
133     return unless ( defined fileno LOG );
134
135     close LOG;
136     &status("Closed logfile ($file{log}).");
137 }
138
139 #####
140 # Usage: &compress($file);
141 sub compress {
142     my ($file) = @_;
143     my @compress = ( '/usr/bin/bzip2', '/bin/bzip2', '/bin/gzip' );
144     my $okay = 0;
145
146     if ( !-f $file ) {
147         &WARN("compress: file ($file) does not exist.");
148         return 0;
149     }
150
151     if ( -f "$file.gz" or -f "$file.bz2" ) {
152         &WARN('compress: file.(gz|bz2) already exists.');
153         return 0;
154     }
155
156     foreach (@compress) {
157         next unless ( -x $_ );
158
159         &status("Compressing '$file' with $_.");
160         system("$_ $file &");
161         $okay++;
162         last;
163     }
164
165     if ( !$okay ) {
166         &ERROR('no compress program found.');
167         return 0;
168     }
169
170     return 1;
171 }
172
173 sub DEBUG {
174     return unless ( &IsParam('DEBUG') );
175
176     &status("${b_green}!DEBUG!$ob $_[0]");
177 }
178
179 sub ERROR {
180     &status("${b_red}!ERROR!$ob $_[0]");
181 }
182
183 sub WARN {
184     return unless ( &IsParam('WARN') );
185
186     return if ( $_[0] =~ /^PERL: Subroutine \S+ redefined at/ );
187
188     &status("${b_yellow}!WARN!$ob $_[0]");
189 }
190
191 sub FIXME {
192     &status("${b_cyan}!FIXME!$ob $_[0]");
193 }
194
195 sub TODO {
196     &status("${b_cyan}!TODO!$ob $_[0]");
197 }
198
199 sub VERB {
200     if ( !&IsParam('VERBOSITY') ) {
201
202         # NOTHING.
203     }
204     elsif ( $param{'VERBOSITY'} eq '1' and $_[1] <= 1 ) {
205         &status( $_[0] );
206     }
207     elsif ( $param{'VERBOSITY'} eq '2' and $_[1] <= 2 ) {
208         &status( $_[0] );
209     }
210 }
211
212 sub status {
213     my ($input) = @_;
214     my $status;
215
216     if ( $input =~ /PERL: Use of uninitialized/ ) {
217         &debug_perl($input);
218         return;
219     }
220
221     if ( $input eq $logold ) {
222         $logrepeat++;
223         return;
224     }
225
226     $logold = $input;
227
228     # if only I had followed how sysklogd does it, heh. lame me. -xk
229     if ( $logrepeat >= 3 ) {
230         &status("LOG: last message repeated $logrepeat times");
231         $logrepeat = 0;
232     }
233
234     # if it's not a scalar, attempt to warn and fix.
235     my $ref = ref $input;
236     if ( defined $ref and $ref ne '' ) {
237         &WARN("status: 'input' is not scalar ($ref).");
238
239         if ( $ref eq 'ARRAY' ) {
240             foreach (@$input) {
241                 &WARN("status: '$_'.");
242             }
243         }
244     }
245
246     # Something is using this w/ NULL.
247     if ( !defined $input or $input =~ /^\s*$/ ) {
248         $input = 'ERROR: Blank status call? HELP HELP HELP';
249     }
250
251     for ($input) {
252         s/\n+$//;
253         s/\002|\037//g;    # bold,video,underline => remove.
254     }
255
256     # does this work?
257     if ( $input =~ /\n/ ) {
258         foreach ( split /\n/, $input ) {
259             &status($_);
260         }
261     }
262
263     # pump up the stats.
264     $statcount++;
265
266     # fix style of output if process is child.
267     if ( defined $bot_pid and $$ != $bot_pid and !defined $statcountfix ) {
268         $statcount    = 1;
269         $statcountfix = 1;
270     }
271
272     ### LOG THROTTLING.
273     ### TODO: move this _after_ printing?
274     my $time  = time();
275     my $reset = 0;
276
277     # hrm... what is this supposed to achieve? nothing I guess.
278     if ( $logtime == $time ) {
279         if ( $logcount < 25 ) {    # too high?
280             $logcount++;
281         }
282         else {
283             sleep 1;
284             &status('LOG: Throttling.');
285             $reset++;
286         }
287     }
288     else {                         # $logtime != $time.
289         $reset++;
290     }
291
292     if ($reset) {
293         $logtime  = $time;
294         $logcount = 0;
295     }
296
297     # Log differently for forked/non-forked output.
298     if ($statcountfix) {
299         $status = "!$statcount! " . $input;
300         if ( $statcount > 1000 ) {
301             print LOG "ERROR: FORKED PROCESS RAN AWAY; KILLING.\n";
302             print LOG 'VERB: ' . ( &Time2String( $time - $forkedtime ) ) . "\n";
303             exit 0;
304         }
305     }
306     else {
307         $status = "[$statcount] " . $input;
308     }
309
310     if ( &IsParam('backlog') ) {
311         push( @backlog, $status );    # append to end.
312         shift(@backlog) if ( scalar @backlog > $param{'backlog'} );
313     }
314
315     if ( &IsParam('VERBOSITY') ) {
316         if ($statcountfix) {
317             printf $_red. '!%6d!' . $ob . ' ', $statcount;
318         }
319         else {
320             printf $_green. '[%6d]' . $ob . ' ', $statcount;
321         }
322
323         # three uberstabs to Derek Moeller. I don't remember why but he
324         # deserved it :)
325         my $printable = $input;
326
327         if ( $printable =~ s/^(<\/\S+>) // ) {
328
329             # it's me saying something on a channel
330             my $name = $1;
331             print "$b_yellow$name $printable$ob\n";
332         }
333         elsif ( $printable =~ s/^(<\S+>) // ) {
334
335             # public message on channel.
336             my $name = $1;
337
338             if ($addressed) {
339                 print "$b_red$name $printable$ob\n";
340             }
341             else {
342                 print "$b_cyan$name$ob $printable$ob\n";
343             }
344
345         }
346         elsif ( $printable =~ s/^\* (\S+)\/(\S+) // ) {
347
348             # public action.
349             print "$b_white*$ob $b_cyan$1$ob/$b_blue$2$ob $printable\n";
350
351         }
352         elsif ( $printable =~ s/^(-\S+-) // ) {
353
354             # notice
355             print "$_green$1 $printable$ob\n";
356
357         }
358         elsif ( $printable =~ s/^(\* )?(\[\S+\]) // ) {
359
360             # message/private action from someone
361             print "$b_white$1$ob" if ( defined $1 );
362             print "$b_red$2 $printable$ob\n";
363
364         }
365         elsif ( $printable =~ s/^(>\S+<) // ) {
366
367             # i'm messaging someone
368             print "$b_magenta$1 $printable$ob\n";
369
370         }
371         elsif ( $printable =~ s/^(enter:|update:|forget:) // ) {
372
373             # something that should be SEEN
374             print "$b_green$1 $printable$ob\n";
375
376         }
377         else {
378             print "$printable\n";
379         }
380
381     }
382     else {
383
384         #print "VERBOSITY IS OFF?\n";
385     }
386
387     # log the line into a file.
388     return unless ( &IsParam('logfile') );
389     return unless ( defined fileno LOG );
390
391     # remove control characters from logging to LOGFILE.
392     for ($input) {
393         last if ( &IsParam('logColors') );
394         s/\e\[[0-9;]+m//g;    # escape codes.
395         s/[\cA-\c_]//g;       # control chars.
396     }
397     $input = "FORK($$) " . $input if ($statcountfix);
398
399     my $date;
400     if ( &IsParam('logType') and $param{'logType'} =~ /DAILY/i ) {
401         $date = sprintf( '%02d:%02d.%02d', ( gmtime $time )[ 2, 1, 0 ] );
402
403         my ( $day, $month, $year ) = ( gmtime $time )[ 3, 4, 5 ];
404         my $newlogDate =
405           sprintf( '%04d%02d%02d', $year + 1900, $month + 1, $day );
406         if ( defined $logDate and $newlogDate != $logDate ) {
407             &closeLog();
408             &compress( $file{log} );
409             &openLog();
410         }
411     }
412     else {
413         $date = $time;
414     }
415
416     printf LOG "%s %s\n", $date, $input;
417 }
418
419 sub debug_perl {
420     my ($str) = @_;
421
422     return
423       unless (
424         $str =~ /^WARN: Use of uninitialized value .* at (\S+) line (\d+)/ );
425     my ( $file, $line ) = ( $1, $2 );
426     if ( !open( IN, $file ) ) {
427         &status("WARN: cannot open $file: $!");
428         return;
429     }
430     binmode( IN, ':encoding(UTF-8)' );
431
432     # TODO: better filename.
433     open( OUT, '>>debug.log' );
434     binmode( OUT, ':encoding(UTF-8)' );
435     print OUT "DEBUG: $str\n";
436
437     # note: cannot call external functions because SIG{} does not allow us to.
438     my $i;
439     while (<IN>) {
440         chop;
441         $i++;
442
443         # bleh. this tries to duplicate status().
444         # TODO: statcountfix
445         # TODO: rename to log_*someshit*
446         if ( $i == $line ) {
447             my $msg = "$file: $i:!$_";
448             printf "%s[%6d]%s %s\n", $_green, $statcount, $ob, $msg;
449             print OUT "DEBUG: $msg\n";
450             $statcount++;
451             next;
452         }
453         if ( $i + 3 > $line && $i - 3 < $line ) {
454             my $msg = "$file: $i: $_";
455             printf "%s[%6d]%s %s\n", $_green, $statcount, $ob, $msg;
456             print OUT "DEBUG: $msg\n";
457             $statcount++;
458         }
459     }
460     close IN;
461     close OUT;
462 }
463
464 sub openSQLDebug {
465     if ( !open( SQLDEBUG, ">>$param{'SQLDebug'}" ) ) {
466         &ERROR("Cannot open ($param{'SQLDebug'}): $!");
467         delete $param{'SQLDebug'};
468         return 0;
469     }
470     binmode( SQLDEBUG, ':encoding(UTF-8)' );
471
472     &status("Opened SQL Debug file: $param{'SQLDebug'}");
473     return 1;
474 }
475
476 sub closeSQLDebug {
477     close SQLDEBUG;
478
479     &status("Closed SQL Debug file: $param{'SQLDebug'}");
480 }
481
482 sub SQLDebug {
483     return unless ( &IsParam('SQLDebug') );
484
485     return unless ( fileno SQLDEBUG );
486
487     print SQLDEBUG $_[0] . "\n";
488 }
489
490 1;
491
492 # vim:ts=4:sw=4:expandtab:tw=80