首頁  >  文章  >  系統教程  >  如何使用logrotate管理Linux日誌文件

如何使用logrotate管理Linux日誌文件

WBOY
WBOY轉載
2024-02-10 11:00:04664瀏覽

Linux系統中的日誌檔案是記錄系統運作和排查故障的重要資源,但是隨著時間的推移,日誌檔案會不斷增長,佔用大量的磁碟空間,也不利於日誌的檢視和分析。為了解決這個問題,我們可以使用logrotate工具來自動地對日誌檔案進行輪換、壓縮、刪除和郵件發送等操作,從而實現日誌檔案的有效管理。本文將介紹logrotate工具的基本原理、設定檔和常用選項,以及如何為不同的應用程式設定logrotate策略。

如何使用logrotate管理Linux日誌文件

logrotate 是如何運作的

預設情況下,logrotate 命令作為放在 /etc/cron.daily 中的 cron 任務,每天運行一次,它會幫助你設定一個策略,其中超過某個時間或大小的日誌檔案被輪換。
指令:

/usr/sbin/logrotate

設定檔: /etc/logrotate.conf,這是 logrotate 的主設定檔。 logrotate 也在 /etc/logrotate.d/ 中儲存了特定服務的設定。確保下面的那行包含在 /etc/logrotate.conf 中,以讀取特定服務日誌配置。

include  /etc/logrotate.d`

logrotate 歷史: /var/lib/logrotate.status

#重要的 logrotate 選項:

compress             --> 压缩日志文件的所有非当前版本
daily,weekly,monthly --> 按指定计划轮换日志文件
delaycompress        --> 压缩所有版本,除了当前和下一个最近的
endscript            --> 标记 prerotate 或 postrotate 脚本的结束
errors "emailid"     --> 给指定邮箱发送错误通知
missingok            --> 如果日志文件丢失,不要显示错误
notifempty           --> 如果日志文件为空,则不轮换日志文件
olddir "dir"         --> 指定日志文件的旧版本放在 “dir” 中
postrotate           --> 引入一个在日志被轮换后执行的脚本
prerotate            --> 引入一个在日志被轮换前执行的脚本
rotate 'n'           --> 在轮换方案中包含日志的 n 个版本
sharedscripts        --> 对于整个日志组只运行一次脚本
size='logsize'       --> 在日志大小大于 logsize(例如 100K,4M)时轮换

配置

讓我們為我們自己的範例日誌檔案 /tmp/sample_output.log 設定 logrotate。

第一步:在 /etc/logrotate.conf 中新增以下行。

/tmp/sample_output.log {
  size 1k
  create 700 root root
  rotate 4
  compress
}

在上面的設定檔中:

size 1k - logrotate 仅在文件大小等于(或大于)此大小时运行。
create - 轮换原始文件并创建具有指定权限、用户和组的新文件。
rotate - 限制日志文件轮转的数量。因此,这将只保留最近的 4 个轮转的日志文件。
compress - 这将压缩文件。

第二步:通常,你需要等待一天才能等到 logrotate 由 /etc/cron.daily 執行。除此之外,你可以用下面的命令在命令列中運行:

/usr/sbin/logrotate  /etc/logrotate.conf

在執行 logrotate 指令之前的輸出:

[root@rhel1 tmp]# ls -l /tmp/
total 28
-rw-------. 1 root root 20000 Jan 1 05:23 sample_output.log

在執行 logrotate 之後的輸出:

[root@rhel1 tmp]# ls -l /tmp
total 12
-rwx------. 1 root root 0 Jan 1 05:24 sample_output.log
-rw-------. 1 root root 599 Jan 1 05:24 sample_output.log-20170101.gz
[root@rhel1 tmp]#

這樣就能確認 logrotate 成功實現了。

透過本文的介紹,我們了解了logrotate工具的作用和用法,以及如何根據不同的需求自訂logrotate策略。 logrotate工具可以幫助我們節省磁碟空間,提高日誌檔案的可讀性和可用性,也方便我們對日誌檔案進行備份和監控。 logrotate工具是Linux系統中一個非常實用的日誌管理工具,值得我們掌握使用。

以上是如何使用logrotate管理Linux日誌文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:lxlinux.net。如有侵權,請聯絡admin@php.cn刪除