What are the best practices for implementing a file writer/logger in Java that is compatible with logrotate? The goal would be allow logrotate to be used for all log management, instead of using built-in rotation/management of a logging API (Log4J, etc).
I'd be interested in hearing comments/answers for other development platforms, aside from Java.
Logrotate is a system utility that manages the automatic rotation and compression of log files. If log files were not rotated, compressed, and periodically pruned, they could eventually consume all available disk space on a system.
If you want to force Logrotate to rotate the log file when it otherwise would not have, use the --force flag: logrotate /home/sammy/logrotate. conf --state /home/sammy/logrotate-state --verbose --force.
By default, the installation of logrotate creates a crontab file inside /etc/cron. daily named logrotate. As it is the case with the other crontab files inside this directory, it will be executed daily starting at 6:25 am if anacron is not installed.
You simply need to periodically close and re-open the log file inside your application. You need a handler that keeps last close time. The handler should close and reopens the file if (for example) 20 seconds passed since last close and log entry is about to be written. It should make such check just before writing the log entry
If you don't do it, the logs will be written to the old file even if it is renamed by logrotate (!) (file descriptor remains the same) and then later the log entries will disappear when the log is compressed and removed (in such case java will silently drop such logs).
Closing and reopening the log (using file name) will make sure that if the file has been renamed a new one will be created. Closing and reopening the file every time log is written is an overkill because opening a file is a costly operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With