systemd服務的輸出重定向到指定文件


有一種更優雅的方法可以解決systemd輸出到指定文件而非/var/log/message,需要使用systemd參數與rsyslog過濾器。並指示syslog過濾器按程序名稱拆分其輸出。

systemd所需參數為

  • SyslogIdentifierrequired,設置日志標識符(發送日志消息時加在行首的字符串)("syslog tag")。 默認值是進程的名稱。此選項僅在 StandardOutput= 或 StandardError= 的值包含 journal(+console), syslog(+console), kmsg(+console) 之一時才有意義, 並且僅適用於輸出到標准輸出或標准錯誤的日志消息。
  • StandardOutputrequired,設置進程的標准輸出(STDOUT)。 可設為 inherit, null, tty, journal, syslog, kmsg, journal+console, syslog+console, kmsg+console, file:path, append:path, socket, fd:name 之一。
  • StandardError:設置進程的標准錯誤(STDERR)。 取值范圍及含義與 StandardOutput= 相同。但有如下例外: (1) inherit 表示使用 StandardOutput= 的值。 (2) fd:name 的默認文件描述符名稱為 "stderr"

rsyslog過濾器設置

  使用rsyslog條件選擇器。如果不改變rsyslog目前工作模式,按照如下操作:

  1. 新建/etc/rsyslog.d/xx.conf文件

  2. 在新建文件內寫入內容如下

單一條件處理。

if $programname == 'programname' then /var/log/programname.log
# 停止往其他文件內寫入,如果不加此句,會繼續往/var/log/message寫入。
if $programname == 'programname' then stop  

多條件處理

  會根據不同應用名稱將不同的輸出日志重定向到不同的文件內。

if ($programname == 'apiserver') then {
   action(type="omfile" file="/var/log/apiserver.log")
   stop
} else if ($programname == 'scheduler') then {
   action(type="omfile" file="/var/log/scheduler.log")
   stop
} else if ($programname == 'controller-manager') then {
   action(type="omfile" file="/var/log/controller-manager.log")
   stop
} else if ($programname == 'etcd') then {
   action(type="omfile" file="/var/log/etcd.log")
   stop
}
  1. 檢查語法是否正確 rsyslogd -N1 -f file_name.conf

  2. 重新啟動rsyslog

  完成以上步驟后,應用的 stdout stderr被重定向到對應的日志文件內了,而非/var/log/message,並且仍然可以通過通過journalctl獲得對應的stdout stderr (systemd參數機制)。

reference

systemd
rsyslog-conditional
rsyslog


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM