]> git.donarmstrong.com Git - infobot.git/blob - src/logger.pl
- renamed Factoids/Misc.pl to Factoids/Core.pl
[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);
13 use vars qw(@backlog);
14 use vars qw(%param %file);
15
16 require 5.001;
17
18 $logtime        = time();
19 $logcount       = 0;
20 $logrepeat      = 0;
21 $logold         = "";
22
23 $param{VEBOSITY} ||= 1;         # lame fix for preload
24
25 my %attributes = (
26         'clear'      => 0,
27         'reset'      => 0,
28         'bold'       => 1,
29         'underline'  => 4,
30         'underscore' => 4,
31         'blink'      => 5,
32         'reverse'    => 7,
33         'concealed'  => 8,
34         'black'      => 30,     'on_black'   => 40,
35         'red'        => 31,     'on_red'     => 41,
36         'green'      => 32,     'on_green'   => 42,
37         'yellow'     => 33,     'on_yellow'  => 43,
38         'blue'       => 34,     'on_blue'    => 44,
39         'magenta'    => 35,     'on_magenta' => 45,
40         'cyan'       => 36,     'on_cyan'    => 46,
41         'white'      => 37,     'on_white'   => 47
42 );
43
44 use vars qw($b_black $_black $b_red $_red $b_green $_green
45             $b_yellow $_yellow $b_blue $_blue $b_magenta $_magenta
46             $b_cyan $_cyan $b_white $_white $_reset $_bold $ob $b);
47
48 $b_black        = cl('bold black');     $_black         = cl('black');
49 $b_red          = cl('bold red');       $_red           = cl('red');
50 $b_green        = cl('bold green');     $_green         = cl('green');
51 $b_yellow       = cl('bold yellow');    $_yellow        = cl('yellow');
52 $b_blue         = cl('bold blue');      $_blue          = cl('blue');
53 $b_magenta      = cl('bold magenta');   $_magenta       = cl('magenta');
54 $b_cyan         = cl('bold cyan');      $_cyan          = cl('cyan');
55 $b_white        = cl('bold white');     $_white         = cl('white');
56 $_reset         = cl('reset');          $_bold          = cl('bold');
57 $ob             = cl('reset');          $b              = cl('bold');
58
59 ############################################################################
60 # Implementation (attribute string form)
61 ############################################################################
62
63 # Return the escape code for a given set of color attributes.
64 sub cl {
65     my @codes = map { split } @_;
66     my $attribute = '';
67     foreach (@codes) {
68         $_ = lc $_;
69         unless (defined $attributes{$_}) { die "Invalid attribute name $_" }
70         $attribute .= $attributes{$_} . ';';
71     }
72     chop $attribute;
73     ($attribute ne '') ? "\e[${attribute}m" : undef;
74 }
75
76 # logging support.
77 sub openLog {
78     return unless (&IsParam("logfile"));
79     $file{log} = $param{'logfile'};
80
81     my $error = 0;
82     my $path = &getPath($file{log});
83     while (! -d $path) {
84         if ($error) {
85             &ERROR("openLog: failed opening log to $file{log}; disabling.");
86             delete $param{'logfile'};
87             return;
88         }
89
90         &status("openLog: making $path.");
91         last if (mkdir $path, 0755);
92         $error++;
93     }
94
95     if (&IsParam("logType") and $param{'logType'} =~ /DAILY/i) {
96         my ($day,$month,$year) = (localtime time())[3,4,5];
97         $logDate = sprintf("%04d%02d%02d",$year+1900,$month+1,$day);
98         $file{log} .= "-".$logDate;
99     }
100
101     if (open(LOG, ">>$file{log}")) {
102         &status("Opened logfile $file{log}.");
103         LOG->autoflush(1);
104     } else {
105         &status("cannot open logfile $file{log}; not logging.");
106     }
107 }
108
109 sub closeLog {
110     # lame fix for paramlogfile.
111     return unless (&IsParam("logfile"));
112     return unless (defined fileno LOG);
113
114     close LOG;
115     &status("Closed logfile ($file{log}).");
116 }
117
118 #####
119 # Usage: &compress($file);
120 sub compress {
121     my ($file) = @_;
122     my @compress = ("/usr/bin/bzip2","/bin/gzip");
123     my $okay = 0;
124
125     if (! -f $file) {
126         &WARN("compress: file ($file) does not exist.");
127         return 0;
128     }
129
130     if ( -f "$file.gz" or -f "$file.bz2" ) {
131         &WARN("compress: file.(gz|bz2) already exists.");
132         return 0;
133     }
134
135     foreach (@compress) {
136         next unless ( -x $_);
137
138         &status("Compressing '$file' with $_.");
139         system("$_ $file &");
140         $okay++;
141         last;
142     }
143
144     if (!$okay) {
145         &ERROR("no compress program found.");
146         return 0;
147     }
148
149     return 1;
150 }
151
152 sub DEBUG {
153     return unless (&IsParam("DEBUG"));
154
155     &status("${b_green}!DEBUG!$ob $_[0]");
156 }
157
158 sub ERROR {
159     &status("${b_red}!ERROR!$ob $_[0]");
160 }
161
162 sub WARN {
163     return unless (&IsParam("WARN"));
164
165     return if ($_[0] =~ /^PERL: Subroutine \S+ redefined at/);
166
167     &status("${b_yellow}!WARN!$ob $_[0]");
168 }
169
170 sub FIXME {
171     &status("${b_cyan}!FIXME!$ob $_[0]");
172 }
173
174 sub TODO {
175     &status("${b_cyan}!TODO!$ob $_[0]");
176 }
177
178 sub VERB {
179     if (!&IsParam("VERBOSITY")) {
180         # NOTHING.
181     } elsif ($param{'VERBOSITY'} eq "1" and $_[1] <= 1) {
182         &status($_[0]);
183     } elsif ($param{'VERBOSITY'} eq "2" and $_[1] <= 2) {
184         &status($_[0]);
185     }
186 }
187
188 sub status {
189     my($input) = @_;
190     my $status;
191
192     if ($input eq $logold) {
193         # allow perl flooding
194         $logrepeat++ unless ($input =~ /PERL: Use of uninitialized/);
195
196         # todo: prevent massive repetitive throttling.
197         if ($logrepeat >= 3) {
198             $logrepeat = 0;
199             &status("LOG: repeat throttle.");
200             sleep 1;
201         }
202     } else {
203         $logold = $input;
204     }
205
206     # if it's not a scalar, attempt to warn and fix.
207     my $ref = ref $input;
208     if (defined $ref and $ref ne "") {
209         &status("status: 'input' is not scalar ($ref).");
210
211         if ($ref eq "ARRAY") {
212             foreach (@$input) {
213                 &WARN("status: '$_'.");
214             }
215         }
216     }
217
218     # Something is using this w/ NULL.
219     if (!defined $input or $input =~ /^\s*$/) {
220         $input = "Blank status call? HELP HELP HELP";
221     }
222
223     for ($input) {
224         s/\n+$//;
225         s/\002|037//g;  # bold,video,underline => remove.
226     }
227
228     # does this work?
229     if ($input =~ /\n/) {
230         foreach (split(/\n/, $input)) {
231             &status($_);
232         }
233     }
234
235     # pump up the stats.
236     $statcount++;
237
238     # fix style of output if process is child.
239     if (defined $bot_pid and $$ != $bot_pid and !defined $statcountfix) {
240         $statcount      = 1;
241         $statcountfix   = 1;
242     }
243
244     ### LOG THROTTLING.
245     ### TODO: move this _after_ printing?
246     my $time    = time();
247     my $reset   = 0;
248
249     if ($logtime == $time) {
250         if ($logcount < 25) {                   # too high?
251             $logcount++;
252         } else {
253             sleep 1;
254             &status("LOG: Throttling.");        # recursive?
255             $reset++;
256         }
257     } else {    # $logtime != $time.
258         $reset++;
259     }
260
261     if ($reset) {
262         $logtime        = $time;
263         $logcount       = 0;
264     }
265
266     # Log differently for forked/non-forked output.
267     if ($statcountfix) {
268         $status = "!$statcount! ".$input;
269         if ($statcount > 1000) {
270             print LOG "ERROR: FORKED PROCESS RAN AWAY; KILLING.\n";
271             print LOG "VERB: ".(&Time2String($time - $forkedtime))."\n";
272             exit 0;
273         }
274     } else {
275         $status = "[$statcount] ".$input;
276     }
277
278     if (&IsParam("backlog")) {
279         push(@backlog, $status);        # append to end.
280         shift(@backlog) if (scalar @backlog > $param{'backlog'});
281     }
282
283     if (&IsParam("VERBOSITY")) {
284         if ($statcountfix) {
285             printf $_red."!%6d!".$ob." ", $statcount;
286         } else {
287             printf $_green."[%6d]".$ob." ", $statcount;
288         }
289
290         # three uberstabs to Derek Moeller.
291         my $printable = $input;
292
293         if ($printable =~ s/^(<\/\S+>) //) {
294             # it's me saying something on a channel
295             my $name = $1;
296             print "$b_yellow$name $printable$ob\n";
297         } elsif ($printable =~ s/^(<\S+>) //) {
298             # public message on channel.
299             my $name = $1;
300
301             if ($addressed) {
302                 print "$b_red$name $printable$ob\n";
303             } else {
304                 print "$b_cyan$name$ob $printable$ob\n";
305             }
306
307         } elsif ($printable =~ s/^\* (\S+)\/(\S+) //) {
308             # public action.
309             print "$b_white*$ob $b_cyan$1$ob/$b_blue$2$ob $printable\n";
310         } elsif ($printable =~ s/^(-\S+-) //) {
311             # notice
312             print "$_green$1 $printable$ob\n";
313         } elsif ($printable =~ s/^(\* )?(\[\S+\]) //) {
314             # message/private action from someone
315             print "$b_white$1$ob" if (defined $1);
316             print "$b_red$2 $printable$ob\n";
317         } elsif ($printable =~ s/^(>\S+<) //) {
318             # i'm messaging someone
319             print "$b_magenta$1 $printable$ob\n";
320         } elsif ($printable =~ s/^(enter:|update:|forget:) //) {
321             # something that should be SEEN
322             print "$b_green$1 $printable$ob\n";
323         } else {
324             print "$printable\n";
325         }
326     } else {
327         print "VERBOSITY IS OFF?\n";
328     }
329
330     # log the line into a file.
331     return unless (&IsParam("logfile"));
332     return unless (defined fileno LOG);
333
334     # remove control characters from logging.
335     for ($input) {
336         s/\e\[[0-9;]+m//g;      # escape codes.
337         s/[\cA-\c_]//g;         # control chars.
338     }
339     $input = "FORK($$) ".$input if ($statcountfix);
340
341     my $date;
342     if (&IsParam("logType") and $param{'logType'} =~ /DAILY/i) {
343         $date = sprintf("%02d:%02d.%02d", (localtime $time)[2,1,0]);
344
345         my ($day,$month,$year) = (localtime $time)[3,4,5];
346         my $newlogDate = sprintf("%04d%02d%02d",$year+1900,$month+1,$day);
347         if (defined $logDate and $newlogDate != $logDate) {
348             &closeLog();
349             &compress($file{log});
350             &openLog();
351         }
352     } else {
353         $date   = $time;
354     }
355
356     print LOG sprintf("%s %s\n", $date, $input);
357 }
358
359 sub openSQLDebug {
360     if (!open(SQLDEBUG, ">>$param{'SQLDebug'}")) {
361         &ERROR("cannot open $param{'SQLDebug'}...");
362         delete $param{'SQLDebug'};
363         return 0;
364     }
365
366     &status("Opened SQL Debug file: $param{'SQLDebug'}");
367     return 1;
368 }
369
370 sub closeSQLDebug {
371     close SQLDEBUG;
372
373     &status("Closed SQL Debug file: $param{'SQLDebug'}");
374 }
375
376 sub SQLDebug {
377     return unless (&IsParam("SQLDebug"));
378
379     return unless (fileno SQLDEBUG);
380
381     print SQLDEBUG $_[0]."\n";
382 }
383
384 1;