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

No comments:

Post a Comment