如何使用rsyslog高级格式(RainerScript)实现日志轮转?
如何使用rsyslog高级格式(RainerScript)实现日志轮转?
嗨,我来帮你搞定这个问题~其实在RainerScript(也就是你说的高级格式)里,完全不用再依赖旧的$outchannel语法,直接给omfile动作加上对应参数就能实现日志轮转,我给你分两种常见场景说明:
场景1:用rsyslog内置功能实现基础轮转(无需外部脚本)
这种方式最简洁,直接在你现有的omfile动作里添加轮转相关参数即可,对应你原来$outchannel里的大小限制和文件保留逻辑:
module(load="imudp") input(type="imudp" port="514" ruleset="forward") ruleset(name="forward") { action(type="omfwd" protocol="tcp" target="127.0.0.1" port="40514" TCP_Framing="octet-counted" KeepAlive="on" action.resumeRetryCount="-1" queue.type="linkedlist" queue.size="50000") # 修改后的omfile动作,添加轮转参数 action(type="omfile" file="/var/log/rsyslog_debug.log" Template="RSYSLOG_DebugFormat" # 单个日志文件最大大小(和你之前的50MB一致) maxFilesize="52428800" # 开启日志轮转功能 action.fileEnableRotation="on" # 保留的轮转文件数量(比如保留10个旧日志) action.maxNumberOfFiles="10" # 轮转文件的命名方式:按数字递增(log.log.1、log.log.2...) action.fileRotateType="number" # 可选:设置日志文件的权限和所属用户组 fileOwner="syslog" fileGroup="adm" fileCreateMode="0640" ) }
每个参数的作用我都标在注释里了,你可以根据实际需求调整maxNumberOfFiles或者maxFilesize的值。
场景2:配合自定义脚本实现复杂轮转逻辑
如果你需要在轮转后执行自定义操作(比如压缩旧日志、发送告警通知),可以用action.onRotate参数指定你的脚本路径,和你原来的rotation.sh配合使用:
module(load="imudp") input(type="imudp" port="514" ruleset="forward") ruleset(name="forward") { action(type="omfwd" protocol="tcp" target="127.0.0.1" port="40514" TCP_Framing="octet-counted" KeepAlive="on" action.resumeRetryCount="-1" queue.type="linkedlist" queue.size="50000") action(type="omfile" file="/var/log/rsyslog_debug.log" Template="RSYSLOG_DebugFormat" maxFilesize="52428800" action.fileEnableRotation="on" action.maxNumberOfFiles="10" # 轮转完成后执行自定义脚本 action.onRotate="/apps/syslogagent/rotation.sh" ) }
注意:rsyslog会把刚轮转完成的日志文件路径作为参数传给脚本,你可以在rotation.sh里用$1来获取这个路径(比如echo "轮转了文件:$1" >> /var/log/rotation.log)。
备注:内容来源于stack exchange,提问作者Elliott B
相关产品推荐
相关产品推荐

