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