Fluentd解析Nginx日志时正则匹配失败问题求助
Nginx日志Fluentd解析匹配失败问题
配置与环境
Fluentd配置
<source> @type tail <parse> @type regexp expression /^(?<remote>[^ ]*) (?<host>[^ ]*) (?<user>[^ ]*) \[(?<time>[^\]]*)\] \"(?<method>\w+) (?<path>[^ ]*) (?<http>[^ ]*)\" (?<status_code>[^ ]*) (?<size>[^ ]*)(?:\s\"(?<referer>[^\"]*)\") \"(?<agent>[^\"]*)\" (?<urt>[^\"]*).*/ time_format %d/%b/%Y:%H:%M:%S %z keep_time_key true types size:integer,reqtime:float,uct:float,uht:float,urt:float </parse> path /var/log/nginx/access.log pos_file /tmp/fluent_nginx.pos tag nginx </source>
Nginx日志示例
193.137.78.17 - - [07/Jan/2023:09:21:59 +0000] "GET /net/api/employee HTTP/1.1" 200 2323 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" 0.014 193.137.78.17 - - [07/Jan/2023:09:22:00 +0000] "GET /net/api/employee HTTP/1.1" 200 2323 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36" 0.005
错误提示
Jan 07 09:26:26 srv-api fluentd[14878]: 2023-01-07 09:26:26 +0000 [warn]: #0 no patterns matched tag="nginx"
正则在regex101测试匹配正常,但Fluentd触发无匹配警告,以下是解决方法:
解决方法
- 修正XML中的正则转义:Fluentd的XML配置会优先解析转义字符,原正则里的
\"需要改为\\",否则XML会将其解析为普通引号,导致正则实际匹配的内容和预期不符。修正后的表达式:/^(?<remote>[^ ]*) (?<host>[^ ]*) (?<user>[^ ]*) \[(?<time>[^\]]*)\] \\"(?<method>\w+) (?<path>[^ ]*) (?<http>[^ ]*)\" (?<status_code>[^ ]*) (?<size>[^ ]*)(?:\s\\"(?<referer>[^\\"]*)\") \\"(?<agent>[^\\"]*)\" (?<urt>[^ ]*).*/ - 修正
urt字段的匹配规则:日志中最后一个字段是数字(如0.014),原正则用[^\"]*匹配不符合实际,改为[^ ]*匹配任意非空白字符更准确,避免引号相关的匹配干扰。 - 重置pos文件:删除
/tmp/fluent_nginx.pos,让Fluentd从头读取日志,排除pos文件记录的偏移位置导致读取不完整日志行的问题。 - 检查日志实际内容:用
cat -v /var/log/nginx/access.log查看日志是否包含不可见字符(如控制字符、特殊换行符),这些字符可能导致正则匹配失败。 - 开启调试输出:添加stdout输出规则,查看Fluentd实际读取的日志行,确认和测试样本一致:
<match *> @type stdout </match>
内容的提问来源于stack exchange,提问作者Antônio Godinho
相关产品推荐
相关产品推荐

