2

I'm using Log::Log4perl to create log files, but it is appending to a single log file; instead, I want to create a separate log file for each execution of my script.

How can I create separate log files ?

Here is my code :

fetch.pl

#Opening Log configuration file
Log::Log4perl::init('./logs/log4perl.conf');
my $logger = Log::Log4perl->get_logger('./logs_$$.logs');

logs.conf

log4perl.logger = TRACE,  FileAppndr1
log4perl.logger.logs = DEBUG, FileAppndr1
log4perl.appender.FileAppndr1 = Log::Log4perl::Appender::File
log4perl.appender.FileAppndr1.filename = logs.log 
log4perl.appender.FileAppndr1.layout = Log::Log4perl::Layout::SimpleLayout
reinierpost
  • 8,425
  • 1
  • 38
  • 70
Naghaveer R
  • 2,890
  • 4
  • 30
  • 52

2 Answers2

2

To get variable interpolation in strings you'll have to use double quotes:

my $logger = Log::Log4perl->get_logger("./logs_$$.logs");

Or concatenation:

my $logger = Log::Log4perl->get_logger('./logs_' . $$ . '.logs');
Biffen
  • 6,249
  • 6
  • 28
  • 36
  • I have changed it to double quotes in fetch.pl But Same thing again. Actually it is creating log file with logs.log which I have mentioned in logs.conf file. – Naghaveer R Apr 03 '14 at 10:34
  • I don't think you're using the `get_logger()` sub right, I can't find any example in the documentation of using it with a file name. As for the file name, you might have to set it up programmatically. The `filename` part in the log is not right, right? – Biffen Apr 03 '14 at 10:40
  • Same logs.conf file I'm using to create logs. But it is creating with log.logs. I'm unable to set programmatically. How to set it? Do I need to change anything in logs.conf? – Naghaveer R Apr 03 '14 at 11:58
  • @user123 I don't *know*, but my best *guess* is that the hardcoded filename in the conf would have to go. – Biffen Apr 03 '14 at 12:18
1

The logfile name is set in the config file, not in the call to get_logger(). So you need to find out how to use variables in the config file. The Log4Perl FAQ contains the question "What if I need dynamic values in a static Log4perl configuration file?"

The important part of the answer is:

As of Log::Log4perl 0.28, every value in the configuration file can be specified as a Perl hook. So, instead of saying

log4perl.appender.Logfile.filename = test.log

you could just as well have a Perl subroutine deliver the value dynamically:

log4perl.appender.Logfile.filename = sub { logfile(); };

given that logfile() is a valid function in your main package returning a string containing the path to the log file.

So it looks like you want:

log4perl.appender.FileAppndr1.filename = sub { "logs_$$.log" };
Dave Cross
  • 68,119
  • 3
  • 51
  • 97