在 CentOS 中自定义消息模板的常用做法
一 使用 rsyslog 定义日志消息模板
$template MyCustomFormat,"%timegenerated:::date-rfc3339% %syslogseverity-text%.%syslogfacility-text% %syslogtag%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n"
常用属性:%timegenerated%、%syslogtag%、%msg%、%hostname%、%programname%、%syslogseverity-text%、%syslogfacility-text%。*.* action(type="omfile" file="/var/log/custom.log" template="MyCustomFormat")
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
*.* ?MyCustomFormat
& stop
sudo systemctl restart rsyslog
sudo systemctl enable rsyslog
logger -t test "this is a custom template message"
tail -f /var/log/custom.log
二 自定义登录前与登录后的消息模板
sudo tee /etc/issue <<'EOF'
\S
Kernel \r on an \m
Hostname: \n
Time: \t
EOF
sudo tee /etc/motd <<'EOF'
Welcome to CentOS Linux
Please read the compliance notice before use.
EOF
sudo tee /etc/profile.d/welcome.sh >/dev/null <<'EOF'
#!/bin/bash
echo -e "\e[1;36m$(hostname)\e[0m logged in at $(date '+%F %T')"
echo -e "Uptime: $(uptime -p)"
EOF
sudo chmod +x /etc/profile.d/welcome.sh
三 自定义系统广播与桌面通知模板
echo -e "$(date '+%F %T') [NOTICE] Maintenance at 22:00–23:00. Save your work." | wall
# 安装(最小化系统按需安装)
sudo yum install -y libnotify
# 发送示例
notify-send "系统告警" "磁盘使用率超过 80%:/dev/sda1"
#!/usr/bin/env bash
journalctl -f -p err --since "1 min ago" | while IFS= read -r line; do
notify-send "Journal ERROR" "$line"
done
# 安装
sudo yum install -y esmtp mailx
# 配置 /etc/mail.rc(示例,按实际 SMTP 调整)
cat >>/etc/mail.rc <<'EOF'
set smtp=smtp://smtp.example.com:587
set smtp-auth=login
set smtp-auth-user=yourname
set smtp-auth-password=yourpass
set ssl-verify=ignore
set nss-config-dir=/etc/pki/nssdb
EOF
# 发送(模板化主题与正文)
SUBJECT="[$(hostname)] $(date '+%F %T') 磁盘告警"
BODY="主机: $(hostname)\n时间: $(date '+%F %T')\n详情: /dev/sda1 使用率 > 80%"
echo -e "$BODY" | mail -s "$SUBJECT" admin@example.com
四 实用模板示例与排错要点
$template JSONFormat,"{\"@timestamp\":\"%timegenerated:::date-rfc3339%\",\"host\":\"%hostname%\",\"severity\":\"%syslogseverity-text%\",\"facility\":\"%syslogfacility-text%\",\"tag\":\"%syslogtag%\",\"msg\":\"%msg:::json%\"}\n"
*.* action(type="omfile" file="/var/log/app.json" template="JSONFormat")
$template KVFormat,"time=%timegenerated:::date-rfc3339% host=%hostname% sev=%syslogseverity-text% fac=%syslogfacility-text% tag=%syslogtag% msg=%msg%\n"
local0.* action(type="omfile" file="/var/log/local0_kv.log" template="KVFormat")
sudo rsyslogd -N1 -f /etc/rsyslog.conf 做语法检查。ausearch -m avc -ts recent 与 setsebool -P rsyslogd_can_write_var_log 1 处理。systemctl status rsyslog 为 active;远程发送需开放 UDP/TCP 514 并配置相应规则。