linux - Set line maximum of log file
问题描述
Currently I write a simple logger to log messages from my bash script. The logger works fine and I simply write the date plus the message in the log file. Since the log file will increase, I would like to set the limit of the logger to for example 1000 lines. After reaching 1000 lines, it doesn't delete or totally clear the log file. It should truncate the first line and replace it with the new log line. So the file keeps 1000 lines and doesn't increase further. The latest line should always be at the top of the file. Is there any built in method? Or how could I solve this?
解决方案
Your chosen example may not be the best. As the comments have already pointed out, logrotate
is the best tool to keep log file sizes at bay; furthermore, a line is not the best unit to measure size. Those commenters are both right.
However, I take your question at face value and answer it.
You can achieve what you want by shell builtins, but it is much faster and simpler to use an external tool like sed
. (awk
is another option, but it lacks the -i
switch which simplifies your life in this case.)
So, suppose your file exists already and is named script.log
then
maxlines=1000
log_msg='Whatever the log message is'
sed -i -e1i"\\$log_msg" -e$((maxlines))',$d' script.log
does what you want.
-i
means modify the given file in place.-e1i"\\$log_msg"
means insert$log_msg
before the first (1) line.-e$((maxlines))',$d'
means delete each line from line number$((maxlines))
to the last one ($).
推荐阅读
- python - 如何用计算数组索引列?
- html - 通过带有按钮的代码旋转网页
- python - '布尔对象不可调用' pygame
- css - Laravel-以创建形式检索旧值文本框
- mysql - 将表结构从 mysql 更改为 sqllite
- node.js - 如果 Content-Type 应用程序/json,Azure 函数不响应
- flutter - CustomPainter - shouldRepaint 值得付出努力吗?
- twitter-bootstrap - 在 iPhone 上的 Bootstrap 4 中删除粘性页脚下的空白
- java - 使用 cxf 类创建和填充非常大的自动生成
- sql - 函数式编程和 SQL