大网数据广告活动
服务器运维问答

Continuously tailing a rotating log file with date and time in filename

· 52CE 我爱测

I have a log file in format log_name_YY-MM-DD_HH_mm.log . The log rotates every couple of hours and the new log is created containing the date and time of it's creation. Sometimes I need to tail the live output of this log with t…

问题原文

原帖链接 · CyberMuz · CC BY-SA 3.0

I have a log file in format log_name_YY-MM-DD_HH_mm.log. The log rotates every couple of hours and the new log is created containing the date and time of it's creation. Sometimes I need to tail the live output of this log with the tail -f command. After the log is rotated tail still points to old filename and must be manually restarted with the new filename.

Is there a way to automatically switch tail -f to use the new file? The tail -F option (tail --follow=name --retry) doesn't work in this case because the filename of the log changes.

已采纳解答

原帖链接 · NZD · CC BY-SA 3.0

You can create a script to tail the most recent log file in the background and then check regularly for a new log file. If there is a new log file, kill the old process and start tailing the new file.

Something like:

#!/bin/bash

PATTERN='log_name_??-??-??_??_??.log'

CURRENT=any_pattern # dummy pattern to start off first tail -f

while true; do
   NEWLOG=`ls -t $PATTERN|head -n1`
   if [[ $NEWLOG != $CURRENT ]]
   then
      kill $TAILPID 2>/dev/null
      CURRENT=$NEWLOG
      tail -f $CURRENT &
      TAILPID=$!
   fi
   sleep 1 # check regularly
done

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-02-25)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。