Search code examples
perlloggingprintinglog4perl

Perl Log4perl Printing and logging at the same time in a line


I'm reading this and I am confused and stuck.

Should I use ALWAYS or print_portfolio('themessage') to both print and log into a file at the same time?

What I want to do:

if ($logfile) {
   open (FILE, '>>', "logfile");
   print "Hello" #some code from Log4perl#;
   #prints on the display and into the logfile
}

instead of:

if ($logfile) { open (FILE, '>>', "logfile"); }
print "Hello";
if ($logfile) { print FILE "Hello"; }

Solution

  • You use neither.

    • ALWAYS is a log level that will always print regardless of the logging level selected. Logging levels are a way of controlling how much information is logged by the logger based on the level selected

    • The print_portfolio subroutine is an example that doesn't really have much to do with logging to screen and file at the same time.

    I believe the Advanced configuration within Perl section has a clear example on how to set up the logger to print to screen and file at the same time:

    Here's an example on how to configure two appenders with the same layout in Perl, without using a configuration file at all:

    ########################
    # Initialization section
    ########################
    use Log::Log4perl;
    use Log::Log4perl::Layout;
    use Log::Log4perl::Level;
    
       # Define a category logger
    my $log = Log::Log4perl->get_logger("Foo::Bar");
    
       # Define a layout
    my $layout = Log::Log4perl::Layout::PatternLayout->new("[%r] %F %L %m%n");
    
       # Define a file appender
    my $file_appender = Log::Log4perl::Appender->new(
                            "Log::Log4perl::Appender::File",
                            name      => "filelog",
                            filename  => "/tmp/my.log");
    
       # Define a stdout appender
    my $stdout_appender =  Log::Log4perl::Appender->new(
                            "Log::Log4perl::Appender::Screen",
                            name      => "screenlog",
                            stderr    => 0);
    
       # Have both appenders use the same layout (could be different)
    $stdout_appender->layout($layout);
    $file_appender->layout($layout);
    
    $log->add_appender($stdout_appender);
    $log->add_appender($file_appender);
    $log->level($INFO);