improve watchdbg and grepdbg
[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                         if ($line =~ m{(?:$exp)}oi) {
47                                 printit(@prev); 
48                                 @prev = ();
49                         }
50                 } else {
51                         printit($line);
52                 }
53         } else {
54                 sleep(1);
55                 
56                 # check that the debug hasn't rolled over to next day
57                 # open it if it has
58                 my @now = Julian::unixtoj(time()); 
59                 if ($today[1] != $now[1]) {
60                         $fp->close;
61                         my $i;
62                         for ($i = 0; $i < 20; $i++) {
63                                 last if $fh = $fp->open(@now);
64                                 sleep 5;
65                         }
66                         die $! if $i >= 20; 
67                         @today = @now;
68                 }
69         }
70 }
71
72 sub printit
73 {
74         while (@_) {
75                 my $line = shift;
76                 my @line =  split '\^', $line;
77                 my $t = shift @line;
78                 my ($sec,$min,$hour) = gmtime((defined $t) ? $t : time);
79                 my $buf = sprintf "%02d:%02d:%02d", $hour, $min, $sec;
80                 
81                 print $buf, ' ', join('^', @line); 
82         }
83 }
84 exit(0);