Last active
June 30, 2022 16:36
-
-
Save DeeNewcum/2491262e974221606dc1ae4d4eb8594d to your computer and use it in GitHub Desktop.
log rotation in Perl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use File::Temp (); | |
# Call the external command https://linux.die.net/man/8/logrotate | |
# with the specified string to be placed inside a config file. | |
# | |
# Returns true if it seemed to have run without error. | |
sub do_logrotate { | |
my ($config_directives, $is_verbose) = @_; | |
# $is_verbose is optional, and defaults to false | |
# Unfortunately 'logrotate' demands that its configuration file be located | |
# inside a regular file, so we can't simply pipe the config in. | |
# see -- https://github.com/logrotate/logrotate/blob/3.20.1/config.c#L1007-L1013 | |
my ($temp_fh, $temp_filename) = File::Temp::tempfile(); | |
print $temp_fh $config_directives; | |
close $temp_fh; | |
my @cmd = ('/usr/sbin/logrotate'); | |
push(@cmd, '-v') if ($is_verbose); | |
push(@cmd, $temp_filename); | |
system(@cmd); | |
return ($? >= 0 && ($? >> 8) == 0); | |
} | |
do_logrotate(<<'EOF'); | |
# for syntax, see https://manpages.debian.org/bullseye/logrotate/logrotate.8.en.html#CONFIGURATION_FILE | |
compress | |
/var/log/myapp.log { | |
# keep 5 copies of the file around | |
rotate 5 | |
# rotate daily | |
daily | |
# don't throw an error if the file doesn't currently exist | |
missingok | |
# no 'postrotate' directive is needed, as long as we know for sure that | |
# the filehandle is closed at this point | |
} | |
EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment