added some comments
[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 2 PCPROT       # watch all PCPROT messages + up to 2 lines before
10 #   watchdbg gb7baa gb7djk   # watch the conversation between BAA and DJK 
11 #
12
13 require 5.004;
14
15 # search local then perl directories
16 BEGIN {
17         # root of directory tree for this system
18         $root = "/spider"; 
19         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
20         
21         unshift @INC, "$root/perl";     # this IS the right way round!
22         unshift @INC, "$root/local";
23 }
24
25 use IO::File;
26 use DXVars;
27 use DXUtil;
28 use DXLog;
29
30 use strict;
31
32 my $fp = DXLog::new('debug', 'dat', 'd');
33 my @today = Julian::unixtoj(time()); 
34 my $fh = $fp->open(@today) or die $!; 
35 my $nolines = 1;
36 $nolines = shift if $ARGV[0] =~ /^\d+$/;
37 my $exp = join '|', @ARGV;
38 my @prev;
39
40 # seek to end of file
41 $fh->seek(0, 2);
42 for (;;) {
43         my $line = <$fh>;
44         if ($line) {
45                 if ($exp) {
46                         push @prev, $line;
47                         shift @prev while @prev > $nolines; 
48                         if ($line =~ m{(?:$exp)}oi) {
49                                 printit(@prev); 
50                                 @prev = ();
51                         }
52                 } else {
53                         printit($line);
54                 }
55         } else {
56                 sleep(1);
57                 
58                 # check that the debug hasn't rolled over to next day
59                 # open it if it has
60                 my @now = Julian::unixtoj(time()); 
61                 if ($today[1] != $now[1]) {
62                         $fp->close;
63                         my $i;
64                         for ($i = 0; $i < 20; $i++) {
65                                 last if $fh = $fp->open(@now);
66                                 sleep 5;
67                         }
68                         die $! if $i >= 20; 
69                         @today = @now;
70                 }
71         }
72 }
73
74 sub printit
75 {
76         while (@_) {
77                 my $line = shift;
78                 chomp $line;
79                 $line =~ s/([\x00-\x1f\x7f-\xff])/sprintf("\\x%02X", ord($1))/eg; 
80                 my @line =  split '\^', $line;
81                 my $t = shift @line;
82                 my ($sec,$min,$hour) = gmtime((defined $t) ? $t : time);
83                 my $buf = sprintf "%02d:%02d:%02d", $hour, $min, $sec;
84                 
85                 print $buf, ' ', join('^', @line), "\n"; 
86         }
87 }
88 exit(0);