magewish4
magewish4

Reputation: 23

How to timestamp application output with perl

I have a command line app that gives command line output as it runs. When I write it to a file (ex: app >> log.txt) it all shows up in the text file just like it appeared in terminal. I need to be able to timestamp the output so that if I leave it running I can come back and see when it printed.

I have tried piping to a perl script:

#!/usr/bin/env perl
use strict;
use warnings;
while (<STDIN>) {
  print time.": $. : $_";
}

Using this command:

./app | perl timestamp.pl >> test.log 2>&1

But the log is empty. I'm sorry I can't be more specific about the application I'm running.

Upvotes: 2

Views: 1290

Answers (2)

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118158

More than likely, @mob's answer solved your immediate problem. However, I would recommend you look into using Log::Log4perl in easy mode. It will help you avoid re-inventing the wheel several times, and you'll get easily configurable logging levels for free:

#!/usr/bin/env perl

use strict; use warnings;

use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init($WARN);

while (<>) {
    INFO "$. : $_";
    if ( /easy/ and ($. > 1)) {
        ERROR "$ARGV [$.] - Make easy things harder!";
    }
    if (eof) {
        ALWAYS "Done with $ARGV";
    }
}
C:\temp> log.pl log.pl
2012/07/07 20:41:57 log.pl [5] - Make easy things harder!
2012/07/07 20:41:57 log.pl [6] - Make easy things harder!
2012/07/07 20:41:57 log.pl [10] - Make easy things harder!
2012/07/07 20:41:57 log.pl [11] - Make easy things harder!
2012/07/07 20:41:57 Done with log.pl

Note also:

While this has been proven to work well familiarizing people with Log::Logperl slowly, effectively avoiding to clobber them over the head with a plethora of different knobs to fiddle with (categories, appenders, levels, layout), the overall mission of Log::Log4perl is to let people use categories right from the start to get used to the concept. So, let's keep this one fairly hidden in the man page (congrats on reading this far :).

Upvotes: 0

mob
mob

Reputation: 118665

Suffering from buffering? Set

$| = 1;

at the top of your script.

Upvotes: 4

Related Questions