Perl script to colorize output

I dunno about you but I tend to pore over quite a few logs throughout the day looking for various output of web applications. To make it a tad easier, I've written up a small little Perl script to apply ANSI colors to certain lines.

 1  #!/usr/bin/perl
 2  use strict;
 3  use Term::ANSIColor qw(:constants);
 4  $|=1;
 6  $Term::ANSIColor::AUTORESET = 1;
 8  my $op = shift || '/^ERR/';
 9  my $makered = eval "sub { $op }";
11  while (<>) {
12      chomp;
13      if (&$makered) {
14          print BOLD RED $_;
15      }
16      else {
17          print $_;
18      }
19      print "\n";
20  }
21  __END__

You can supply Perl code that returns a boolean for lines that you are looking for as the first argument. It reads the input from STDIN and outputs the desired lines in red. By default, it looks for lines that start with "ERR". So far, I've been using it with tail:

     tail -f svcerr.log | colorize '/find this text/'
     tail -f svcerr.log | colorize '$_ eq "foo"'
     tail -f svcerr.log | colorize 'length($_) > 50'

Needless to say, Perl does most of the work and makes this really easy. Now you may be asking yourself, why not just use grep to just pull out all the lines you want? I like seeing the lines around the lines I'm looking for (especially if there are stack traces in it) so this script makes it easier to pick out the lines I'm looking for. Maybe my Unix-foo isn't up to snuff and this is indeed possible with grep or some other Unix program?

1 Comment

I've been attempting to make sense of an approach to all the more effectively shading content in Perl as I do on Bash on a Linux box. In bash, what I'll do is set shading factors up to level with the escape arrangement, at that point resound out with escape seqeunces to print it precisely how I need it Best Essay Writing Service. Normally I'll need a character or a word in an alternate shading, not the entire line.

Leave a comment