How to use the Logger in Perl

Home > Search > How-to
  by

This assumes you have installed the Log:Log4perl module on your system.

The following script is a example of how to use the logger in easy mode. In this example script, the logger is initialized, and then the user will be prompted to enter a number. If "1" is entered, the logger will log the event at level info. Else, the logger will log the event a level error.

#!/usr/bin/perl
#############################
# Initialize the logger
#############################
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init({
    level   => $INFO,
    layout  => '%d{MMM-dd-yyyy HH:mm:ss,SSS} %-5p %m%n'
});
my $logger = Log::Log4perl->get_logger();

#############################
# Main Routine
#############################
print "Enter an integer: \n";
my $integer = <STDIN>;
chomp $integer;

if ($i eq 1) {
  $logger->info("Success!");
} else {
  $logger->error("Failure!");
}

 

When this script is run, if "1" is entered, the following will be displayed.

~]# perl example.pl
Enter an integer: 1
[May-19-2018 17:45:23,142] INFO Success!

 

If anything other than "1" is entered, the following will be displayed.

~]# perl example.pl
Enter an integer: 7
[May-19-2018 17:45:23,142] ERROR Failure!

 

Since every one of your scripts will probably use the logger, it makes sense to place the initialization section of this example script into a custom module.



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments