]> git.donarmstrong.com Git - infobot.git/blob - src/logger.pl
make sure chanstats don't flood
[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         # ironically this does not get logged :)
127         &WARN("compress: file ($file) does not exist.");
128         return 0;
129     }
130
131     if (-f "$file.gz" or -f "$file.bz2") {
132         &WARN("compress: file.(gz|bz2) already exists.");
133         return 0;
134     }
135
136     foreach (@compress) {
137         next unless ( -x $_);
138
139         &status("Compressing '$file' with $_.");
140         system("$_ $file &");
141         $okay++;
142         last;
143     }
144
145     if (!$okay) {
146         &ERROR("no compress program found.");
147         return 0;
148     }
149
150     return 1;
151 }
152
153 sub DEBUG {
154     return unless (&IsParam("DEBUG"));
155
156     &status("${b_green}!DEBUG!$ob $_[0]");
157 }
158
159 sub ERROR {
160     &status("${b_red}!ERROR!$ob $_[0]");
161 }
162
163 sub WARN {
164     return unless (&IsParam("WARN"));
165
166     return if ($_[0] =~ /^PERL: Subroutine \S+ redefined at/);
167
168     &status("${b_yellow}!WARN!$ob $_[0]");
169 }
170
171 sub FIXME {
172     &status("${b_cyan}!FIXME!$ob $_[0] (SHOULD NOT HAPPEN?)");
173 }
174
175 sub TODO {
176     &status("${b_cyan}!TODO!$ob $_[0]");
177 }
178
179 sub VERB {
180     if (!&IsParam("VERBOSITY")) {
181         # NOTHING.
182     } elsif ($param{'VERBOSITY'} eq "1" and $_[1] <= 1) {
183         &status($_[0]);
184     } elsif ($param{'VERBOSITY'} eq "2" and $_[1] <= 2) {
185         &status($_[0]);
186     }
187 }
188
189 sub status {
190     my($input) = @_;
191     my $status;
192
193     if ($input eq $logold) {
194         $logrepeat++ unless (/!WARN! PERL: Use of uninitialized/);
195
196         if ($logrepeat >= 3) {
197             $logrepeat = 0;
198             &status("LOG: repeat throttle.");
199             sleep 1;
200         }
201     }
202     $logold = $input;
203
204     # if it's not a scalar, attempt to warn and fix.
205     if (ref($input) ne "") {
206         &status("status: 'input' is not scalar (".ref($input).").");
207         if (ref($input) eq "ARRAY") {
208             foreach (@$input) {
209                 &WARN("status: '$_'.");
210             }
211         }
212     }
213
214     # Something is using this w/ NULL.
215     if (!defined $input or $input =~ /^\s*$/) {
216         $input = "Blank status call?";
217     }
218     $input =~ s/\n+$//;
219     $input =~ s/\002|037//g;    # bold,video,underline => remove.
220
221     # pump up the stats (or loglinenum).
222     $statcount++;
223
224     # fix style of output if process is child.
225     if (defined $bot_pid and $$ != $bot_pid and !defined $statcountfix) {
226         $statcount      = 1;
227         $statcountfix   = 1;
228     }
229
230     ### LOG THROTTLING.
231     ### TODO: move this _after_ printing?
232     my $time = time();
233     my $reset = 0;
234     if ($logtime != $time) {
235         $reset++;
236     } elsif ($logtime == $time) {
237         if ($logcount < 25) {           # too high?
238             $logcount++;
239         } else {
240             sleep 1;
241             &status("LOG: Throttling.");        # recursive?
242             $reset++;
243         }
244     }
245     if ($reset) {
246         $logtime        = $time;
247         $logcount       = 0;
248     }
249
250     # Log differently for forked/non-forked output.
251     if ($statcountfix) {
252         $status = "!$statcount! ".$input;
253         if ($statcount > 1000) {
254             print LOG "ERROR: FORKED PROCESS RAN AWAY; KILLING.\n";
255             print LOG "VERB: ".(&Time2String(time() - $forkedtime))."\n";
256             exit 0;
257         }
258     } else {
259         $status = "[$statcount] ".$input;
260     }
261
262     if (&IsParam("backlog")) {
263         push(@backlog, $status);        # append to end.
264         shift(@backlog) if (scalar @backlog > $param{'backlog'});
265     }
266
267     if (&IsParam("VERBOSITY")) {
268         if ($statcountfix) {
269             printf $_red."!%5d!".$ob." ", $statcount;
270         } else {
271             printf $_green."[%5d]".$ob." ", $statcount;
272         }
273
274         # three uberstabs to Derek Moeller.
275         my $printable = $input;
276
277         if ($printable =~ s/^(<\/\S+>) //) {
278             # it's me saying something on a channel
279             my $name = $1;
280             print "$b_yellow$name $printable$ob\n";
281         } elsif ($printable =~ s/^(<\S+>) //) {
282             # public message on channel.
283             my $name = $1;
284
285             if ($addressed) {
286                 print "$b_red$name $printable$ob\n";
287             } else {
288                 print "$b_cyan$name$ob $printable$ob\n";
289             }
290
291         } elsif ($printable =~ s/^\* (\S+)\/(\S+) //) {
292             # public action.
293             print "$b_white*$ob $b_cyan$1$ob/$b_blue$2$ob $printable\n";
294         } elsif ($printable =~ s/^(-\S+-) //) {
295             # notice
296             print "$_green$1 $printable$ob\n";
297         } elsif ($printable =~ s/^(\* )?(\[\S+\]) //) {
298             # message/private action from someone
299             print "$b_white$1$ob" if (defined $1);
300             print "$b_red$2 $printable$ob\n";
301         } elsif ($printable =~ s/^(>\S+<) //) {
302             # i'm messaging someone
303             print "$b_magenta$1 $printable$ob\n";
304         } elsif ($printable =~ s/^(enter:|update:|forget:) //) {
305             # something that should be SEEN
306             print "$b_green$1 $printable$ob\n";
307         } else {
308             print "$printable\n";
309         }
310     } else {
311         print "VERBOSITY IS OFF?\n";
312     }
313
314     # log the line into a file.
315     return unless (&IsParam("logfile"));
316     return unless (defined fileno LOG);
317
318     # remove control characters from logging.
319     $input =~ s/\e\[[0-9;]+m//g;
320     $input =~ s/[\cA-\c_]//g;
321     $input = "FORK($$) ".$input if ($statcountfix);
322
323     my $date;
324     if (&IsParam("logType") and $param{'logType'} =~ /DAILY/i) {
325         $date = sprintf("%02d:%02d.%02d", (localtime(time()))[2,1,0]);
326
327         my ($day,$month,$year) = (localtime(time()))[3,4,5];
328         my $newlogDate = sprintf("%04d%02d%02d",$year+1900,$month+1,$day);
329         if (defined $logDate and $newlogDate != $logDate) {
330             &closeLog();
331             &compress($file{log});
332             &openLog();
333         }
334     } else {
335         $date = time();
336     }
337
338     print LOG sprintf("%s %s\n", $date, $input);
339 }
340
341 sub openSQLDebug {
342     if (!open(SQLDEBUG, ">>$param{'SQLDebug'}")) {
343         &ERROR("cannot open $param{'SQLDebug'}...");
344         delete $param{'SQLDebug'};
345         return 0;
346     }
347
348     &status("Opened SQL Debug file: $param{'SQLDebug'}");
349     return 1;
350 }
351
352 sub closeSQLDebug {
353     close SQLDEBUG;
354
355     &status("Closed SQL Debug file: $param{'SQLDebug'}");
356 }
357
358 1;