主機

How Smart Tools Are Shaping the Future of Creative Work

Eric Chuang
2020-11-12

雖然兩年前跟阿竣學習自己設定主機環境,但當時只是透過 lnmp.org 的堆疊指令碼 (stack script) 部署環境,其實自己對於 Linux 的指令碼環境還不熟悉,遑論管理紀錄檔 (log) 了。

logrotate 分割 NGINX 紀錄檔

首先,在命令提示字元中,輸入 sudo vim /etc/logrotate.d/nginx 用以建立 NGINX 用的組態檔。

/home/wwwlogs/*.log {
    monthly
    size=100M
    dateext
    missingok
    rotate 12
    compress
    notifempty
    create 640 www www
    su root root
    sharedscripts
    postrotate
        if [ -f /path/to/nginx/logs/nginx.pid ]; then
                kill -USR1 `cat /pat/to/nginx/logs/nginx.pid`
        fi
    endscript
}

由於 lnmp.org 會將紀錄檔儲存於 /home/wwwlogs/ 的資料夾中,因此我們以 /home/wwwlogs/*.log 作為目標。

  • monthly 代表每個月封存一次。
  • size 則是指定檔案超過一定大小後才會封存。以這裡為例,如果當月的紀錄檔未大於 100M 則不會封存。
  • dateext 會以日期作為檔名後綴。可以搭配 dateformat 自訂日期格式。
  • rotate 12 代表保留 12 份封存檔,超過的話則會從最舊的開始刪除。
  • missingok 允許「沒有紀錄檔」。
  • notifempty 允許「紀錄檔沒有內容」。
  • compress 會將封存的紀錄檔以 gzip 壓縮。
  • create 640 www www 是檔案封存後,檔案的權限與擁有者。
  • su root root 用什麼樣的權限執行封存,如果這裡定義 su root root 的話,那麼建立的封存紀錄檔所有權會變成是 root:root 的。
  • sharedscripts 代表執行完所有封存後 (尤其目標檔案使用萬用字元 * 時),才會執行後續的 postrotate/endscript。
  • postrotate/endscript 中間包覆的指令碼,是用來重啟 NGINX 處理程序,並重新啟用紀錄檔。根據 NGINX 的文件, nginx.pid 中紀錄的所有處理程序 ID,而 kill 的指令則可以結束 NGINX 並將其重啟。

在儲存上述的設定檔後,可以執行 sudo logrotate -vf /etc/logrotate.d/nginx 的指令,強制執行封存。

Sign up for our newsletter

Subscribe to our newsletter to receive the latest updates, expert insights, and practical tips directly in your inbox. Stay informed with content designed to help you grow.

+480.000 happy customers

Gain more with expert solutions

Unlock the full potential of your business with our expert solutions. Our team provides tailored strategies, professional guidance, and actionable insights to help you achieve better results.

  • Eric Chuang
  • •
  • 2025-01-23
如何同時使用 Webinoly 與 Cloudflare 保護網站安全

在社群夥伴勇哥的文章〈Webinoly 最新版快速安裝〉中,提到使用 Webinoly 來建立 WordPre […]

主機