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