保持日誌檔案大小固定,無需 logrotate

保持日誌檔案大小固定,無需 logrotate

有什麼方法可以保持日誌檔案的檔案大小固定,而不用新的空檔案旋轉它並刪除(或歸檔)舊檔案。例如,如果我將日誌檔案最大大小設為1MB,則在檔案大小增加超過該限制後,它將自動夾緊,文字將添加到「tail」上,並彈出文字中最舊的部分,以保持文件大小為1MB 。

答案1

您可以編寫一個小 bash 腳本來執行此操作。只需使用尾部檔案達到一定的位元組數tail -c即可覆蓋檔案。

man tail

-c, --bytes=N
              output the last N bytes; alternatively, use +N to  output  bytes
              starting with the Nth of each file

   If  the  first  character of N (the number of bytes or lines) is a `+',
   print beginning with the Nth item from the start of each  file,  other‐
   wise, print the last N items in the file.  N may have a multiplier suf‐
   fix:  b  512,  kB  1000,  K  1024,  MB  1000*1000,  M   1024*1024,   GB
   1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.

答案2

我確信原發文者在 8 年後已經找到了解決方案。這是其他可能閱讀此主題的人的另一篇文章...

curtail 使用以下命令限製程式輸出的大小並保留最後 200MB 的輸出:

運行程式| curtail -s 200M myprogram.log

https://github.com/Comcast/Infinite-File-Curtailer

答案3

您唯一的解決方案可能是編寫自己的使用者空間檔案系統或為現有的檔案系統做出貢獻。查看部分列表使用者空間中的檔案系統

如果您沒有能力做出貢獻,請提供專案宣傳或 $$$ 或兩者兼而有之,以便為您添加。

我希望我有時間去做,我一直想要這樣的東西。

答案4

這是我的第二個答案。這是一個相當駭客的行為。

使用 watch(1) 重複執行tail --bytes=1024(日誌檔案的最後 1024 個位元組,感謝 @jjclarkson 的回答)。

watch --no-title tail --bytes=1024 /var/log/messages >/tmp/messages.watch

然後使用以下命令查看該文件:

less --raw-control-chars /tmp/messages.watch

watch和 while 迴圈之間的差異在於watch,如果 /var/log/messages 發生更改,則只會更新 /tmp/messages.watch 。

while true; do
    tail --bytes=1024 /var/log/messages > /tmp/messages.watch
    sleep 1
done

好吧,我想你可以test在 while 循環中放入一個,以便只有在 /var/log/messages 更新時才執行 tail ,但我現在不知道這一點。

相關內容