Sunday, February 15, 2015

A Simple Perl Logger with Log Timestamp in Milliseconds

A simple Per Logger with log timestamp in milliseconds.
#!/usr/bin/perl
use strict;
use Time::HiRes qw/gettimeofday/;
use POSIX qw/strftime/;

log_error("This is error");
log_info("This is information");

############################################################
# Logger - Error
############################################################
sub log_error {
    my $message = shift;
    log_it( $message, "ERROR" );
}

############################################################
# Logger - Info
############################################################
sub log_info {
    my $message = shift;
    log_it( $message, "INFO" );
}

############################################################
# Logger - Info
############################################################
sub log_it {
    my $message = shift;
    my $level   = shift;
    my ( $time, $ms ) = gettimeofday();
    my $logtimestamp = 
         strftime( "%Y-%m-%d %H:%M:%S", localtime($time) );

    $ms = sprintf( "%03d", $ms / 1000 );
    printf( "%s.%03d %-5s %s\n", 
         $logtimestamp, $ms, $level, $message );
}

Sample Output

2015-02-15 16:27:34.822 ERROR This is error
2015-02-15 16:27:34.823 INFO  This is information

Thursday, January 22, 2015

How to Find UTC Time Offset from your Local Time?

This is the sample script to find the offset in seconds of your local time from GMT.
#!/usr/bin/perl
use strict;

use POSIX;

my @local = localtime();
my @utc   = gmtime();

my $timezone_offset = mktime(@local) - mktime(@utc);

print "Offset in second(s) from GMT = $timezone_offset\n";
print "Offset in hour(s) from GMT = " . ($timezone_offset / 3600) . "\n";

Output:
Offset in second(s) from GMT = 28800
Offset in hour(s) from GMT = 8