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