Skip to main content

Rsyslog

Tutorials

常用指令

# Validate the rsyslog configuration
rsyslogd -N 2 -f /etc/rsyslog.conf

# Restart the rsyslog
systemctl restart rsyslog

整合特定應用程式

情境一: 寫入日誌檔

應用程式透過 rsyslog 協定寫入訊息,系統要輸出特定日誌檔。

/etc/rsyslog.d/myapp.conf

# Save db2audit log to db2audit
# Test command:
# logger -t db2audit -p user.info "Hello, This is Test Message"
if $programname == 'db2audit' then action(type="omfile" file="/var/log/db2audit")
& stop

TIP: 如果不用這判斷式,只用 user.* 格式,其他不相關的應用程式日誌也會一併寫入。

情境二: 讀取日誌檔

應用程式已經有自己的日誌檔,內容也符合 rsyslog 標準日誌格式,需要同步也寫到外部的日誌伺服器。

/etc/rsyslog.d/myapp.conf

$ModLoad imfile

$InputFileName  /app/your-file.log 
$InputFileTag   your-tag
$InputFileStateFile     your-tag 
$InputFileSeverity      info
$InputFileFacility      local7 
$InputRunFileMonitor
$InputFilePersistStateInterval 1000 
local7.*  @@remote-rsyslog-server:port

Central Log Server

Server Configuration

/etc/rsyslog.d/10-from-remote.conf

# Avoid the duplicate messages from local syslog
$template RemoteLogs,"/var/log/%HOSTNAME%/%PROGRAMNAME%.log"
if ($fromhost != "local-server-hostname" ) then ?RemoteLogs
& stop

/etc/rsyslog.conf

# Provides TCP syslog reception
# for parameters see http://www.rsyslog.com/doc/imtcp.html
module(load="imtcp") # needs to be done just once
input(type="imtcp" port="514")
Client Configuration

/etc/rsyslog.d/10-to-remote.conf

# remote host is: name/ip:port, e.g. 192.168.0.1:514, port optional
# Use @@ for TCP protocol, @ for UDP protocol
*.*  @10.4.1.77:514;RSYSLOG_SyslogProtocol23Format
Restrict access to the log server (on Server)

/etc/rsyslog.d/9-acl.conf

# Restrict access to the log server that is sent from
# $AllowedSender <type>, ip[/bits], ip[/bits]
$AllowedSender TCP, 127.0.0.1, 10.15.9.31

FAQ

日誌檔不明原因無法被寫入新日誌

日誌檔一旦被編輯過就無法再被寫入,必須重啟 rsyslog 服務後才會恢復。

AIX: 接收 AIX 主機的 syslog 時無法正確顯示來源 IP

原因:AIX syslog 傳遞至遠端 Log Server 時,預設會自動加上 "Message forwarded by $hostname" 的資訊。要避免這個問題,在啟動 syslogd 服務加上參數 -n

startsrc -s syslogd -a "-n"