PERL: Simple Log file(s) Generation and and colored output on CMD
How to create simple log file that contain Timestamp, Filepath, line number and user message. i.e.
2012-03-22 16:06:30 C:/Automation/lib/Utils.pl : 1569 -- Command Line options are : XYZ How do we print message on CMD in different color based on message type? What is message Type:
- Warning message
- Fatal Error
- Debug information
- General error
- Test case pass
- Test case failed
- Test case review
Perl Code: use strict; use warnings; use Cwd; use vars qw($VERSION); $VERSION = '0.01'; use Color::Output; Color::Output::Init; my %msgColors = ( "debug" => 14, # Cyan "info" => 15, # "white", "warn" => 13, # yellow "error" => 4, #"red", "fatal" => 5, # bold red "Pass" => 6, # Green "Fail" => 4, # Red "Review" => 13 ); my $info_log = "./Info_log.txt"; sub Info_Log() { my ($message,$message_type) = @_; #caller() stores the complete trace of callers when we call a function in a .pl file from another .pl file #both the file names are stored my ($package, $filename, $line, $subr, $has_args, $wantarray )= caller(); #Copy the contents of the return value of caller() method ### Get system cureent time my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time); my $tm = sprintf "%5d-%02d-%02d %02d:%02d:%02d",$year+1900,$mon+1,$mday,$hour,$min,$sec; if($message ne ' ') { #Create a message to show... my $message_string = sprintf("%-10s %-30s : %-5d",$tm,$filename,$line); $message = $message_string." -- ".$message; cprint("\x03".$msgColors{$message_type}."$message\x030\n"); #Define a name of the file for logging #Create instance of the FileOutputter Class open IFH, ">>$info_log" or die "Info log file *$info_log* : can not be opened. : $!"; print IFH "$message\n"; close IFH; } } How to call Info_log function. Info_Log("Can not create process ","fatal"); Info_Log("This is warning message","warn"); Info_Log("This is Error message","error"); Info_Log("Test case failed","fail"); Info_Log("Test case pass","pass"); Info_Log("Normal statement","info"); Info_Log("Debug statement","debug");Colored Output:
Above all statements are also written in info_log.txt file in current directory.
Comments
Post a Comment