Being a fan of simplicity and high maintainability, I made this. I'm open to your opinion.
This command will truncate log file /tmp/myfile
, it cuts the beginning and not the end of the file, it does not require you to configure services and install multi-line scripts; just a one-line command you can add to your crontab.
tail -c 1M /tmp/myfile > /tmp/dzqxH4ZMiSQb91uMMMgPhsgmpnc && rm /tmp/myfile && mv /tmp/dzqxH4ZMiSQb91uMMMgPhsgmpnc /tmp/myfile
First command cuts 1MB of the target file into a temp file, second command deletes the target file, and the third one renames the 1MB temp file as your target file.
It has the disadvantage that it will allocate in your file system, temporarily, 1 MB of space. This could be a problem if you want to keep, say, the last 1 GB of your log file, and your storage is too small or too slow.
If that's your case, you could try this:
fallocate -c -o 0 -l 1M file
It will cut off bytes from your file; starting at position 0, it deallocates 1 MB of disk space off your file. I understand it does it in place, instead of copying data into a temporary file. But it takes more complexity; you would need to first calculate the current size of the file to know how much to deallocate, or make a little loop, something like:
while (file larger than 100M) fallocate 1M;
resulting in a file between 100 MB and 99 MB.
But I like simplicity so for now I'm going with the first option.