Skip to content

Instantly share code, notes, and snippets.

@wh13371
Last active August 29, 2015 14:14
Show Gist options
  • Save wh13371/8abc0b3b3ff8a24d15b6 to your computer and use it in GitHub Desktop.
Save wh13371/8abc0b3b3ff8a24d15b6 to your computer and use it in GitHub Desktop.
perl - rough template thats outputs to screen & log file
#! /usr/bin/perl
use strict;
use warnings;
use 5.010;
use Time::HiRes qw/time gettimeofday/;
use POSIX 'strftime';
use FileHandle ('autoflush');
use Getopt::Std;
my %opt;
sub usage()
{
say "Usage = ???.pl [-v] -l <filename>";
exit 58;
}
sub main()
{
parse_args();
say "VERBOSE ENABLED = [$opt{v}]" if $opt{v};
say "FILE LOGGING ENABLED = [$opt{l}]" if exists $opt{l};
while(1)
{
out("LOG TEST @ epoch " . time());
sleep(1);
}
}
sub parse_args()
{
use Getopt::Std;
my $opt_string = 'vhl:'; # -v=verbose // -h=help // -l = output to log file
getopts( "$opt_string", \%opt ) or usage();
usage() if $opt{h};
if($opt{l})
{
if(!open(LOG,">$opt{l}")) { die "FILE ERROR" };
LOG->autoflush(1);
}
}
# log to screen + if enabled log to file
sub out
{
my $data = shift; # get the "text" to output
my $msg = now() . " : PID[$$] THREAD[$$] FILENAME[$0] STARTTIME[$^T]: " . $data; # $_[0]; # prefix a timestamp
say "$msg"; # to STDOUT
if($opt{l}) # if enabled to FILE
{
say LOG "$msg";
}
}
# a decent "datetime" string
sub now
{
my ($epoch, $microseconds) = gettimeofday;
my $now = strftime( q/%Y:%m:%d %H:%M:%S./, localtime($epoch)) . sprintf("%06d", $microseconds);
return $now;
}
main();
exit 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment