Fluentd out_file插件:1h timekey下实现3s刷新并生成正确日志文件名
问题描述
原本使用forest插件动态生成文件输出路径,现在需要移除该插件,生成格式为app.2023110813-0.log(其中0代表worker_id)的日志文件。当前配置如下:
<match **> #tag cluster.namespace.app @type file @id "save-#{worker_id}" path "fluentd/log/${path_cluster}/${path_namespace}/${path_app}/${path_app}.*-#{worker_id}.log" append true <buffer path_cluster,path_namespace,path_app,time> @type file timekey 1h flush_mode interval flush_interval 3s flush_at_shutdown true </buffer> <format> @type single_value message_key log </format> </match>
但设置1h的timekey后,flush_interval被忽略,日志刷新到文件的时间过长。希望实现每3秒刷新一次日志(以便实时查看),同时生成格式为app.%Y%m%d%H-#{worker_id}.log的文件。尝试过time_slice_format和time_format,但无timekey时日期格式的小时不正确(比如上午11点时显示为2023110800-0)。请问在Fluentd 1.14.2版本下有什么解决办法?
解决方案
核心是正确结合timekey(控制文件切片周期)和flush_interval(控制日志刷新频率),同时配置time_slice_format确保文件名时间戳正确。修改后的配置如下:
<match **> #tag cluster.namespace.app @type file @id "save-#{worker_id}" path "fluentd/log/${path_cluster}/${path_namespace}/${path_app}/${path_app}.%Y%m%d%H-#{worker_id}.log" time_slice_format "%Y%m%d%H" append true <buffer path_cluster,path_namespace,path_app,time> @type file timekey 3600 # 等价于1小时,用秒数配置更直观 flush_mode interval flush_interval 3s flush_at_shutdown true timekey_wait 0 # 关闭默认的10分钟等待,让日志实时写入当前小时文件 </buffer> <format> @type single_value message_key log </format> </match>
关键修改说明:
- 文件名时间戳配置:在
path中直接使用%Y%m%d%H占位符,同时通过time_slice_format "%Y%m%d%H"明确时间格式,确保文件名的小时段与日志事件所属的小时一致。 - buffer参数协调:保留
timekey 3600来按小时划分日志文件,同时设置timekey_wait 0避免默认的延迟写入;flush_mode interval和flush_interval 3s会正常生效——每3秒将累积的日志刷新到当前小时的文件中,到下一个小时自动切换新文件,兼顾实时性和按小时归档的需求。 - 解决小时显示错误:无
timekey时,file插件不会按日志事件时间切片,而是使用buffer初始化时间填充占位符,导致小时错误。通过保留timekey并配合time_slice_format,让文件名时间戳准确对应日志事件的时间区间。
内容的提问来源于stack exchange,提问作者Jane
相关产品推荐
相关产品推荐

