1

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"; }
John Tan
  • 509
  • 3
  • 8
  • 19
  • Thanks to the person who helped edit my post to highlight the code parts. I made another edit to highlight that ALWAYS is actually code and ur name disappeared so I don't know who you are :( – John Tan Dec 23 '11 at 20:38
  • If you click where it says "edited X hours ago", you'll see the revision history of your post, including the name of everyone who's edited it. – cjm Dec 23 '11 at 22:16
  • 1
    The [Log4perl FAQ](http://log4perl.sourceforge.net/releases/Log-Log4perl/docs/html/Log/Log4perl/FAQ.html) answers this, in several ways. – brian d foy Dec 23 '11 at 22:56

1 Answers1

6

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);
Zaid
  • 36,680
  • 16
  • 86
  • 155