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