I would like to capture output from a UNIX process but limit max file size and/or rotate to a new file.
I have seen logrotate, but it does not work real-time. As I understand, it is a "clean-up" job that runs in parallel.
What is the right solution? I guess I will write a tiny script to do it, but I was hoping there was a simple way with existing text tools.
Imagine:
my_program | tee --max-bytes 100000 log/my_program_log
Would give... Always writing latest log file as: log/my_program_log
Then, as it fills... renamed to log/my_program_log000001 and start a new log/my_program_log.
or using awk
It keeps lines together, so the max is not exact, but this could be nice especially for logging purposes. You can use awk's sprintf to format the file name.
Here's a pipable script, using awk
save this to a file called 'bee', run '
chmod +x bee
' and you can use it asor to split an existing file as
The most straightforward way to solve this is probably to use python and the logging module which was designed for this purpose. Create a script that read from
stdin
and write tostdout
and implement the log-rotation described below.The "logging" module provides the
which does exactly what you are asking about.
From docs.python.org
To limit the size to 100 bytes, you can simply use dd:
When 100 bytes are written, dd will close the pipe and my_program receives EPIPE.
In package
apache2-utils
is present utility calledrotatelogs
, it fully meet to your requirements.Synopsis:
rotatelogs [ -l ] [ -L linkname ] [ -p program ] [ -f ] [ -t ] [ -v ] [ -e ] [ -c ] [ -n number-of-files ] logfile rotationtime|filesize(B|K|M|G) [ offset ]
Example:
Full manual you may read on this link.
Another solution will be to use Apache rotatelogs utility.
Or following script:
use split:
Or if you don't want to see the output, you can directly pipe to split:
As for the log rotation, there's no tool in coreutils that does it automatically. You could create a symlink and periodically update it using a bash command: