How to configure Upstart Logrotate?

To configure Upstart to rotate the log file for a particular service, you will need to add a post-start stanza to the service’s configuration file. This stanza should specify the command to run after the service starts, which in this case would be the logrotate command.

Here’s an example of an Upstart configuration file that rotates the log file for a service called myservice:

start on runlevel [2345]
stop on runlevel [016]


console output

post-start script
    logrotate -f /etc/logrotate.d/myservice
end script

exec /usr/bin/myservice

In this example, the logrotate command is run with the -f option, which forces logrotate to rotate the log file even if it is not yet time for the rotation according to the logrotate configuration. You can also specify additional options, such as the log file’s maximum size or the number of copies to keep, in the logrotate command.

It’s also a good idea to specify a pre-stop stanza in the configuration file that rotates the log file one last time before the service is stopped. This ensures that all log messages are captured in the rotated log files.

pre-stop script
    logrotate -f /etc/logrotate.d/myservice
end script

Once you have added the post-start and pre-stop stanzas to the configuration file, you will need to create a logrotate configuration file for the service in /etc/logrotate.d. The configuration file should specify the log file for the service and any options you want to use for rotating the log file, such as the maximum size or the number of copies to keep.

Here’s an example logrotate configuration file for the myservice service:

/var/log/myservice.log {
    size 100M
    rotate 5

This configuration file specifies that the myservice log file should be rotated when it reaches a size of 100MB, and that up to 5 rotated copies should be kept. The log file is also compressed and the compression is delayed until the next rotation.

Once you have created the logrotate configuration file, you can test the rotation by running the logrotate command with the -f option to force a rotation:

logrotate -f /etc/logrotate.d/myservice

If everything is configured correctly, the log file for the myservice service should be rotated and a new log file should be created. You can check the rotated log files in the /var/log directory to make sure they were created and compressed as expected.

Related Solutions