]> git.donarmstrong.com Git - infobot.git/blob - src/logger.pl
avoid reassigning to temp upon decode_utf8
[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 __output {
174     my ($color,$what,$message) = @_;
175     my (undef,undef,$line,$subroutine,undef) = caller(2);
176     use String::Escape qw();
177     status("$color!$what!$ob ".$subroutine.'['.$line.'] '.String::Escape::backslash($message));
178 }
179
180 sub DEBUG {
181     return unless ( &IsParam('DEBUG') );
182     __output($b_green,'DEBUG',$_[0]);
183 }
184
185 sub ERROR {
186     __output($b_red,'ERROR',$_[0]);
187 }
188
189 sub WARN {
190     return unless ( &IsParam('WARN') );
191     return if ( $_[0] =~ /^PERL: Subroutine \S+ redefined at/ );
192     __output($b_yellow,'WARN',$_[0]);
193 }
194
195 sub FIXME {
196     __output($b_cyan,'FIXME',$_[0]);
197 }
198
199 sub TODO {
200     __output($b_cyan,'TODO',$_[0]);
201 }
202
203 sub VERB {
204     if ( !&IsParam('VERBOSITY') ) {
205
206         # NOTHING.
207     }
208     elsif ( $param{'VERBOSITY'} eq '1' and $_[1] <= 1 ) {
209         &status( $_[0] );
210     }
211     elsif ( $param{'VERBOSITY'} eq '2' and $_[1] <= 2 ) {
212         &status( $_[0] );
213     }
214 }
215
216 sub status {
217     my ($input) = @_;
218     my $status;
219
220     if ( $input =~ /PERL: Use of uninitialized/ ) {
221         &debug_perl($input);
222         return;
223     }
224
225     if ( $input eq $logold ) {
226         $logrepeat++;
227         return;
228     }
229
230     $logold = $input;
231
232     # if only I had followed how sysklogd does it, heh. lame me. -xk
233     if ( $logrepeat >= 3 ) {
234         &status("LOG: last message repeated $logrepeat times");
235         $logrepeat = 0;
236     }
237
238     # if it's not a scalar, attempt to warn and fix.
239     my $ref = ref $input;
240     if ( defined $ref and $ref ne '' ) {
241         &WARN("status: 'input' is not scalar ($ref).");
242
243         if ( $ref eq 'ARRAY' ) {
244             foreach (@$input) {
245                 &WARN("status: '$_'.");
246             }
247         }
248     }
249
250     # Something is using this w/ NULL.
251     if ( !defined $input or $input =~ /^\s*$/ ) {
252         $input = 'ERROR: Blank status call? HELP HELP HELP';
253     }
254
255     for ($input) {
256         s/\n+$//;
257         s/\002|\037//g;    # bold,video,underline => remove.
258     }
259
260     # does this work?
261     if ( $input =~ /\n/ ) {
262         foreach ( split /\n/, $input ) {
263             &status($_);
264         }
265     }
266
267     # pump up the stats.
268     $statcount++;
269
270     # fix style of output if process is child.
271     if ( defined $bot_pid and $$ != $bot_pid and !defined $statcountfix ) {
272         $statcount    = 1;
273         $statcountfix = 1;
274     }
275
276     ### LOG THROTTLING.
277     ### TODO: move this _after_ printing?
278     my $time  = time();
279     my $reset = 0;
280
281     # hrm... what is this supposed to achieve? nothing I guess.
282     if ( $logtime == $time ) {
283         if ( $logcount < 25 ) {    # too high?
284             $logcount++;
285         }
286         else {
287             sleep 1;
288             &status('LOG: Throttling.');
289             $reset++;
290         }
291     }
292     else {                         # $logtime != $time.
293         $reset++;
294     }
295
296     if ($reset) {
297         $logtime  = $time;
298         $logcount = 0;
299     }
300
301     # Log differently for forked/non-forked output.
302     if ($statcountfix) {
303         $status = "!$statcount! " . $input;
304         if ( $statcount > 1000 ) {
305             print LOG "ERROR: FORKED PROCESS RAN AWAY; KILLING.\n";
306             print LOG 'VERB: ' . ( &Time2String( $time - $forkedtime ) ) . "\n";
307             exit 0;
308         }
309     }
310     else {
311         $status = "[$statcount] " . $input;
312     }
313
314     if ( &IsParam('backlog') ) {
315         push( @backlog, $status );    # append to end.
316         shift(@backlog) if ( scalar @backlog > $param{'backlog'} );
317     }
318
319     if ( &IsParam('VERBOSITY') ) {
320         if ($statcountfix) {
321             printf $_red. '!%6d!' . $ob . ' ', $statcount;
322         }
323         else {
324             printf $_green. '[%6d]' . $ob . ' ', $statcount;
325         }
326
327         # three uberstabs to Derek Moeller. I don't remember why but he
328         # deserved it :)
329         my $printable = $input;
330
331         if ( $printable =~ s/^(<\/\S+>) // ) {
332
333             # it's me saying something on a channel
334             my $name = $1;
335             print "$b_yellow$name $printable$ob\n";
336         }
337         elsif ( $printable =~ s/^(<\S+>) // ) {
338
339             # public message on channel.
340             my $name = $1;
341
342             if ($addressed) {
343                 print "$b_red$name $printable$ob\n";
344             }
345             else {
346                 print "$b_cyan$name$ob $printable$ob\n";
347             }
348
349         }
350         elsif ( $printable =~ s/^\* (\S+)\/(\S+) // ) {
351
352             # public action.
353             print "$b_white*$ob $b_cyan$1$ob/$b_blue$2$ob $printable\n";
354
355         }
356         elsif ( $printable =~ s/^(-\S+-) // ) {
357
358             # notice
359             print "$_green$1 $printable$ob\n";
360
361         }
362         elsif ( $printable =~ s/^(\* )?(\[\S+\]) // ) {
363
364             # message/private action from someone
365             print "$b_white$1$ob" if ( defined $1 );
366             print "$b_red$2 $printable$ob\n";
367
368         }
369         elsif ( $printable =~ s/^(>\S+<) // ) {
370
371             # i'm messaging someone
372             print "$b_magenta$1 $printable$ob\n";
373
374         }
375         elsif ( $printable =~ s/^(enter:|update:|forget:) // ) {
376
377             # something that should be SEEN
378             print "$b_green$1 $printable$ob\n";
379
380         }
381         else {
382             print "$printable\n";
383         }
384
385     }
386     else {
387
388         #print "VERBOSITY IS OFF?\n";
389     }
390
391     # log the line into a file.
392     return unless ( &IsParam('logfile') );
393     return unless ( defined fileno LOG );
394
395     # remove control characters from logging to LOGFILE.
396     for ($input) {
397         last if ( &IsParam('logColors') );
398         s/\e\[[0-9;]+m//g;    # escape codes.
399         s/[\cA-\c_]//g;       # control chars.
400     }
401     $input = "FORK($$) " . $input if ($statcountfix);
402
403     my $date;
404     if ( &IsParam('logType') and $param{'logType'} =~ /DAILY/i ) {
405         $date = sprintf( '%02d:%02d.%02d', ( gmtime $time )[ 2, 1, 0 ] );
406
407         my ( $day, $month, $year ) = ( gmtime $time )[ 3, 4, 5 ];
408         my $newlogDate =
409           sprintf( '%04d%02d%02d', $year + 1900, $month + 1, $day );
410         if ( defined $logDate and $newlogDate != $logDate ) {
411             &closeLog();
412             &compress( $file{log} );
413             &openLog();
414         }
415     }
416     else {
417         $date = $time;
418     }
419
420     printf LOG "%s %s\n", $date, $input;
421 }
422
423 sub debug_perl {
424     my ($str) = @_;
425
426     return
427       unless (
428         $str =~ /^WARN: Use of uninitialized value .* at (\S+) line (\d+)/ );
429     my ( $file, $line ) = ( $1, $2 );
430     if ( !open( IN, $file ) ) {
431         &status("WARN: cannot open $file: $!");
432         return;
433     }
434     binmode( IN, ':encoding(UTF-8)' );
435
436     # TODO: better filename.
437     open( OUT, '>>debug.log' );
438     binmode( OUT, ':encoding(UTF-8)' );
439     print OUT "DEBUG: $str\n";
440
441     # note: cannot call external functions because SIG{} does not allow us to.
442     my $i;
443     while (<IN>) {
444         chop;
445         $i++;
446
447         # bleh. this tries to duplicate status().
448         # TODO: statcountfix
449         # TODO: rename to log_*someshit*
450         if ( $i == $line ) {
451             my $msg = "$file: $i:!$_";
452             printf "%s[%6d]%s %s\n", $_green, $statcount, $ob, $msg;
453             print OUT "DEBUG: $msg\n";
454             $statcount++;
455             next;
456         }
457         if ( $i + 3 > $line && $i - 3 < $line ) {
458             my $msg = "$file: $i: $_";
459             printf "%s[%6d]%s %s\n", $_green, $statcount, $ob, $msg;
460             print OUT "DEBUG: $msg\n";
461             $statcount++;
462         }
463     }
464     close IN;
465     close OUT;
466 }
467
468 sub openSQLDebug {
469     if ( !open( SQLDEBUG, ">>$param{'SQLDebug'}" ) ) {
470         &ERROR("Cannot open ($param{'SQLDebug'}): $!");
471         delete $param{'SQLDebug'};
472         return 0;
473     }
474     binmode( SQLDEBUG, ':encoding(UTF-8)' );
475
476     &status("Opened SQL Debug file: $param{'SQLDebug'}");
477     return 1;
478 }
479
480 sub closeSQLDebug {
481     close SQLDEBUG;
482
483     &status("Closed SQL Debug file: $param{'SQLDebug'}");
484 }
485
486 sub SQLDebug {
487     return unless ( &IsParam('SQLDebug') );
488
489     return unless ( fileno SQLDEBUG );
490
491     print SQLDEBUG $_[0] . "\n";
492 }
493
494 1;
495
496 # vim:ts=4:sw=4:expandtab:tw=80