change watchdbg and grepdbg to show preceeding lines
[spider.git] / perl / watchdbg
1 #!/usr/bin/perl
2 #
3 # watch the end of the current debug file (like tail -f) applying
4 # any regexes supplied on the command line.
5 #
6 # examples:-
7
8 #   watchdbg g1tlh       # watch everything g1tlh does
9 #   watchdbg gb7baa gb7djk   # watch the conversation between BAA and DJK 
10 #
11
12 require 5.004;
13
14 # search local then perl directories
15 BEGIN {
16         # root of directory tree for this system
17         $root = "/spider"; 
18         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
19         
20         unshift @INC, "$root/perl";     # this IS the right way round!
21         unshift @INC, "$root/local";
22 }
23
24 use IO::File;
25 use DXVars;
26 use DXUtil;
27 use DXLog;
28
29 use strict;
30
31 my $fp = DXLog::new('debug', 'dat', 'd');
32 my @today = Julian::unixtoj(time()); 
33 my $fh = $fp->open(@today) or die $!; 
34 my $nolines = shift if $ARGV[0] =~ /^\d+$/ || 1;
35 my $exp = join '|', @ARGV;
36 my @prev;
37
38 # seek to end of file
39 $fh->seek(0, 2);
40 for (;;) {
41         my $line = <$fh>;
42         if ($line) {
43                 if ($exp) {
44                         push @prev, $line;
45                         shift @prev while @prev > $nolines; 
46                         printit(@prev) if $line =~ m{(?:$exp)}oi;
47                 } else {
48                         printit($line);
49                 }
50         } else {
51                 sleep(1);
52                 
53                 # check that the debug hasn't rolled over to next day
54                 # open it if it has
55                 my @now = Julian::unixtoj(time()); 
56                 if ($today[1] != $now[1]) {
57                         $fp->close;
58                         my $i;
59                         for ($i = 0; $i < 20; $i++) {
60                                 last if $fh = $fp->open(@now);
61                                 sleep 5;
62                         }
63                         die $! if $i >= 20; 
64                         @today = @now;
65                 }
66         }
67 }
68
69 sub printit
70 {
71         while (@_) {
72                 my $line = shift;
73                 my @line =  split '\^', $line;
74                 my $t = shift @line;
75                 my ($sec,$min,$hour) = gmtime((defined $t) ? $t : time);
76                 my $buf = sprintf "%02d:%02d:%02d", $hour, $min, $sec;
77                 
78                 print $buf, ' ', join('^', @line); 
79         }
80 }
81 exit(0);