Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Log4perl rotating my logs daily?

I'm reading up on Log4perl and want to try and use it for simple log management of my Perl scripts running on a Linux box. I've also read up on newsyslog and logrotate but want to use Log4perl if at all possible.

I'm trying to configure the /etc/log4perl.conf file so that it:

  • Defines a widget logger (INFO level) that will write all output to /opt/myapp/logs/myapp-<datetime>.log, where <datetime> is a date/time formatted string like 2012-12-20
  • This myapp-<datetime>.log file needs to be rotated daily (preferably at midnight), where the old file is deleted, and a new file is created with <datetime> + 1. For instance, myapp-2012-12-20.log would be replaced with myapp-2012-12-21.log, etc.

Here's my best attempt which I believe is close, but is still missing some configuration:

#####/etc/log4perl.conf############################################################
log4perl.logger.widget                      = INFO, MyAppLogAppender

log4perl.appender.MyAppLogAppender          = Log::Log4perl::Appender::File
log4perl.appender.MyAppLogAppender.filename = /opt/myapp/logs/myapp-???.log
log4perl.appender.MyAppLogAppender.layout   = Log::Log4perl::Layout::SimpleLayout
###################################################################################

How do I configure log4perl.appender.MyAppLogAppender to rotate once a day, delete the old file, and create a new one with a correct timestamp? Thanks in advance.

like image 217
IAmYourFaja Avatar asked Dec 04 '25 11:12

IAmYourFaja


1 Answers

Here's an example of a Log::Log4perl configuration file, defining a daily rollover at midnight (date pattern yyyy-MM-dd), keeping a maximum of 5 saved logfiles around, at WARN level, and dumping everything to screen:

log4perl.logger                         = TRACE, Screen, Logfile

log4perl.appender.Logfile               = Log::Dispatch::FileRotate
log4perl.appender.Logfile.Threshold     = WARN
log4perl.appender.Logfile.filename      = test.log
log4perl.appender.Logfile.max           = 5
log4perl.appender.Logfile.DatePattern   = yyyy-MM-dd
log4perl.appender.Logfile.TZ            = PST
log4perl.appender.Logfile.layout        = Log::Log4perl::Layout::PatternLayout 
log4perl.appender.Logfile.layout.ConversionPattern = %d %m %n

log4perl.appender.Screen                = Log::Log4perl::Appender::Screen
log4perl.appender.Screen.stderr         = 0
log4perl.appender.Screen.utf8           = 1
log4perl.appender.Screen.layout         = Log::Log4perl::Layout::PatternLayout::Multiline
log4perl.appender.Screen.layout.ConversionPattern = [%p] %m %n

(reference: https://metacpan.org/module/Log::Log4perl::FAQ#How-can-I-roll-over-my-logfiles-automatically-at-midnight-)

like image 155
creaktive Avatar answered Dec 06 '25 03:12

creaktive



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!