Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a logrotate friendly file writer in Java or other platform?

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.

like image 535
nbeyer Avatar asked Jun 28 '11 21:06

nbeyer


People also ask

What is logrotate utility?

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.

How do you run logrotate forcefully?

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.

How do I run logrotate daily?

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.


1 Answers

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.

like image 113
Jarek Potiuk Avatar answered Oct 04 '22 04:10

Jarek Potiuk