rsyslog 配置文件语法详解
1. 配置文件结构
默认配置文件位置
bash
/etc/rsyslog.conf # 主配置文件
/etc/rsyslog.d/*.conf # 附加配置文件
/lib/rsyslog/*.so # 模块目录
配置文件示例(RHEL/CentOS 默认)
bash
# /etc/rsyslog.conf 典型结构
#### MODULES ####
module(load="imuxsock") # 本地系统日志支持
module(load="imjournal") # 从journald读取
#module(load="imklog") # 内核日志(默认注释)
#module(load="immark") # 标记消息
#### GLOBAL DIRECTIVES ####
$WorkDirectory /var/lib/rsyslog
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
#### RULES ####
# 将info及以上级别(不含mail/auth/cron)写入messages
*.info;mail.none;authpriv.none;cron.none /var/log/messages
# authpriv相关日志写入secure
authpriv.* /var/log/secure
# mail日志
mail.* -/var/log/maillog
# cron日志
cron.* /var/log/cron
# 紧急日志给所有用户
*.emerg :omusrmsg:*
# uucp和news的crit级别日志
uucp,news.crit /var/log/spooler
# boot相关日志
local7.* /var/log/boot.log
2. 核心语法元素
A. 模块加载
bash
# 传统语法(v6及之前)
$ModLoad imuxsock
$ModLoad imjournal
# 现代语法(v7+,推荐)
module(load="imuxsock")
module(load="imjournal"
StateFile="imjournal.state"
RateLimit.Interval="0")
B. 规则(Filters + Actions)
bash
# 基本格式
facility.priority target
# 示例
auth.* /var/log/auth.log # auth所有级别
*.info /var/log/messages # 所有facility的info及以上
mail.err @192.168.1.100:514 # 发送到远程服务器
3. 设施(Facility)
| 代码 | 设施 | 描述 |
|---|---|---|
| 0 | kern | 内核消息 |
| 1 | user | 用户级消息 |
| 2 | 邮件系统 | |
| 3 | daemon | 系统守护进程 |
| 4 | auth | 安全/授权消息 |
| 5 | syslog | syslogd内部消息 |
| 6 | lpr | 打印系统 |
| 7 | news | 网络新闻 |
| 8 | uucp | UUCP系统 |
| 9 | cron | 计划任务 |
| 10 | authpriv | 安全/授权消息 |
| 11 | ftp | FTP守护进程 |
| 12 | ntp | NTP子系统 |
| 13 | security | 审计日志 |
| 14 | console | 控制台消息 |
| 15 | solaris-cron | Solaris cron |
| 16-23 | local0-local7 | 本地使用 |
4. 优先级(Priority/Severity)
| 级别 | 代码 | 描述 |
|---|---|---|
| emerg | 0 | 紧急,系统不可用 |
| alert | 1 | 需要立即行动 |
| crit | 2 | 严重错误 |
| err | 3 | 错误条件 |
| warning | 4 | 警告条件 |
| notice | 5 | 正常但重要 |
| info | 6 | 信息性消息 |
| debug | 7 | 调试级别消息 |
特殊关键字:
*:所有优先级none:排除此设施=:仅此优先级(如=info)!:排除此优先级及以上!=:排除此优先级
5. 规则语法详解
A. 基础规则
bash
# 单一设施和优先级
auth.info /var/log/auth.log
# 多个设施(逗号分隔)
auth,authpriv.* /var/log/secure
# 排除特定设施
*.info;mail.none;authpriv.none;cron.none /var/log/messages
# 解释:所有info及以上,但排除mail、authpriv、cron
# 特定优先级
*.=info /var/log/info.log # 仅info级别
*.!=info /var/log/not-info.log # 非info级别
B. 高级选择器
bash
# 优先级范围
kern.warning /var/log/kernel-warn.log # warning及以上
kern.=warning /var/log/kernel-warn.log # 仅warning
kern.!warning /var/log/kernel-other.log # warning以下
# 复合条件
if $programname == 'sshd' then {
action(type="omfile" file="/var/log/sshd.log")
}
6. 动作(Action)语法
A. 文件输出
bash
# 普通文件(实时写入)
*.info /var/log/messages
# 异步写入(- 前缀,提高性能但可能丢失)
mail.* -/var/log/maillog
# 带模板
template(name="MyFormat" type="string" string="%timegenerated% %hostname% %msg%\n")
*.info action(type="omfile" file="/var/log/messages" template="MyFormat")
B. 远程输出
bash
# UDP(@)
*.info @192.168.1.100:514
# TCP(@@)
*.info @@192.168.1.100:514
# RELP(更可靠)
*.info :omrelp:192.168.1.100:2514
C. 用户/程序输出
bash
# 发送给登录用户
*.emerg :omusrmsg:*
*.alert :omusrmsg:root
# 执行程序
:omprog:/usr/bin/my-log-handler
7. 模板(Template)
模板是定义日志输出格式的"配方"------告诉rsyslog每条日志应该以什么样的结构和样式输出。
A. 字符串模板
bash
# 传统格式
$template MyFormat,"%timegenerated% %hostname% %msg%\n"
# 现代格式(推荐)
template(name="MyFormat" type="string" string="%timegenerated% %hostname% %syslogtag% %msg%\n")
B. 列表模板
bash
template(name="MyFormat" type="list") {
constant(value="[")
property(name="timereported" dateFormat="rfc3339")
constant(value="] ")
property(name="hostname")
constant(value=" ")
property(name="syslogtag")
constant(value=": ")
property(name="msg" spifno1stsp="on")
constant(value="\n")
}
C. 常用属性变量
bash
%timegenerated% # 消息接收时间
%timereported% # 消息发送时间
%hostname% # 主机名
%syslogtag% # 标签(程序[PID])
%msg% # 消息内容
%programname% # 程序名
%pri% # 优先级数值
%pri-text% # 优先级文本
8. 变量和属性
A. 系统属性
bash
# 消息属性
$msg # 消息内容
$rawmsg # 原始消息
$hostname # 主机名
$programname # 程序名
$syslogtag # syslog标签
$pri # 优先级数值
$fromhost # 来源主机
$fromhost-ip # 来源IP
# 时间属性
$now # 当前时间戳
$year # 年
$month # 月
$day # 日
$hour # 小时
$minute # 分钟
$second # 秒
B. 自定义变量
bash
# 设置变量
set $!myvar = "value";
# 使用变量
template(name="MyTemplate" type="string" string="Custom: $!myvar %msg%\n")
9. 控制结构
A. 条件语句
bash
# if-else
if $programname == 'sshd' then {
action(type="omfile" file="/var/log/sshd.log")
} else if $programname == 'nginx' then {
action(type="omfile" file="/var/log/nginx.log")
} else {
*.info /var/log/other.log
}
# 基于属性
if $msg contains 'error' then {
action(type="omfile" file="/var/log/errors.log")
}
B. 循环和集合
bash
# 遍历数组(需要mmnormalize等模块)
set $!i = 0;
while $!i < $!array-size do {
set $!element = $!array[$!i];
# 处理元素
set $!i = $!i + 1;
}
10. 模块配置
常用模块配置示例
bash
# imjournal(从journald读取)
module(load="imjournal"
StateFile="/run/log/imjournal.state"
Ratelimit.Interval="0"
Ratelimit.Burst="10000")
# imfile(监控文本文件)
module(load="imfile" PollingInterval="10")
input(type="imfile"
File="/var/log/nginx/access.log"
Tag="nginx-access"
Severity="info"
Facility="local6")
# ommysql(输出到MySQL)
module(load="ommysql")
action(type="ommysql"
server="localhost"
db="Syslog"
uid="rsyslog"
pwd="password")
# omelasticsearch(输出到ES)
module(load="omelasticsearch")
action(type="omelasticsearch"
server="localhost"
serverport="9200"
template="json-template")
11. 高级功能
A. 队列(Queue)
bash
# 主队列配置
$MainMsgQueueType LinkedList # 或 FixedArray, Disk
$MainMsgQueueFileName mainq # 磁盘队列文件名
$MainMsgQueueMaxFileSize 100m # 队列文件大小
$MainMsgQueueSaveOnShutdown on # 关机时保存队列
$MainMsgQueueDequeueSlowdown 100 # 出队延迟(ms)
# 动作队列
action(type="omfile"
file="/var/log/messages"
queue.type="linkedlist"
queue.size="10000"
queue.dequeueBatchSize="100")
B. 过滤器
bash
# 基于属性
:programname, isequal, "sshd" /var/log/sshd.log
# 正则表达式
:msg, regex, "error.*fatal" /var/log/errors.log
# 基于IP
:fromhost-ip, isequal, "192.168.1.100" /var/log/from-100.log
C. 日志轮转
bash
# 传统方式(外部工具)
$ActionFileEnableSync on
$ActionQueueType LinkedList
$ActionQueueFileName acq
$ActionQueueMaxDiskSpace 1g
$ActionQueueSaveOnShutdown on
$ActionQueueTimeoutEnqueue 0
$ActionQueueDiscardMark 975000
$ActionQueueHighWaterMark 800000
$ActionQueueLowWaterMark 200000
$ActionQueueCheckpointInterval 100
12. 调试和测试
A. 配置验证
bash
# 检查语法
rsyslogd -N1
# 或
rsyslogd -f /etc/rsyslog.conf -N1
# 调试模式运行
rsyslogd -dn
B. 测试规则
bash
# 发送测试日志
logger -p user.info "Test message"
logger -t myprogram -p local0.err "Error occurred"
# 测试特定设施和优先级
logger -p auth.info "Auth test"
logger -p cron.warning "Cron warning"
C. 查看内部状态
bash
# 查看队列状态
grep -i queue /var/log/messages
# 查看模块加载
ps aux | grep rsyslog
# 或查看 /proc/<pid>/maps
13. 完整配置文件示例
bash
# /etc/rsyslog.conf
#### MODULES ####
module(load="imuxsock" # 本地系统日志
SysSock.Use="off") # 禁用传统/dev/log
module(load="imjournal" # 从journald读取
StateFile="imjournal.state"
RateLimit.Interval="0")
#### GLOBAL DIRECTIVES ####
$WorkDirectory /var/lib/rsyslog
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
$IncludeConfig /etc/rsyslog.d/*.conf
$OmitLocalLogging on
$IMJournalStateFile imjournal.state
#### TEMPLATES ####
template(name="RemoteFormat" type="list") {
property(name="timestamp" dateFormat="rfc3339")
constant(value=" ")
property(name="hostname")
constant(value=" ")
property(name="syslogtag")
constant(value=" ")
property(name="msg" spifno1stsp="on")
constant(value="\n")
}
#### RULES ####
# 本地日志文件
*.info;mail.none;authpriv.none;cron.none /var/log/messages
authpriv.* /var/log/secure
mail.* -/var/log/maillog
cron.* /var/log/cron
*.emerg :omusrmsg:*
uucp,news.crit /var/log/spooler
local7.* /var/log/boot.log
# 条件日志:nginx
if $programname == 'nginx' then {
if $syslogseverity-text == 'error' then {
action(type="omfile" file="/var/log/nginx/error.log")
} else {
action(type="omfile" file="/var/log/nginx/access.log")
}
}
# 转发到远程服务器(TCP)
*.info @@logserver.example.com:514;RemoteFormat
# 发送到所有用户终端
*.alert :omusrmsg:*
14. 实用小技巧
A. 按日期分割日志
bash
# 使用模板按日期生成文件名
template(name="DynFile" type="string"
string="/var/log/%$year%/%$month%/%$day%/messages.log")
*.info action(type="omfile" dynaFile="DynFile")
B. 限制日志速率
bash
# 限制重复消息
$RepeatedMsgReduction on
# 自定义限速
module(load="mmdblookup")
if $msg contains "Connection refused" then {
# 每60秒只记录一次
set $. = lookup("CONN_REFUSED", $fromhost);
if $. == "" then {
set $. = $now;
action(type="mmdblookup" key="CONN_REFUSED" value=$.)
action(type="omfile" file="/var/log/conn-refused.log")
} else if ($now - $. > 60) then {
set $. = $now;
action(type="omfile" file="/var/log/conn-refused.log")
}
}
C. 性能优化
bash
# 启用批量处理
$ActionQueueType LinkedList
$ActionQueueFileName acq
$ActionQueueMaxDiskSpace 1g
$ActionQueueSaveOnShutdown on
$ActionQueueTimeoutEnqueue 0
# 异步磁盘写入
$ActionFileEnableSync off
$MainMsgQueueTimeoutShutdown 60000
$MainMsgQueueDiscardMark 975000
$MainMsgQueueHighWaterMark 800000
快速参考表
| 语法 | 含义 | 示例 |
|---|---|---|
facility.priority target |
基本规则 | *.info /var/log/messages |
;facility.none |
排除设施 | *.info;mail.none |
-target |
异步写入 | mail.* -/var/log/maillog |
@host:port |
UDP转发 | *.info @192.168.1.100:514 |
@@host:port |
TCP转发 | *.info @@192.168.1.100:514 |
:omusrmsg:* |
用户消息 | *.emerg :omusrmsg:* |
template() |
定义模板 | template(name="fmt" type="string" string="%msg%") |
module(load="") |
加载模块 | module(load="imjournal") |
if condition then {} |
条件语句 | if $programname == 'sshd' then {} |
action() |
定义动作 | action(type="omfile" file="/var/log/test.log") |
提示 :修改配置后,使用 systemctl restart rsyslog 重启服务,或 systemctl reload rsyslog 重新加载(如果支持)。