我已经编写了一个Go程序包github.com/hpcloud/tail来完成此任务。
t, err := tail.TailFile("/var/log/nginx.log", tail.Config{Follow: true})for line := range t.Lines { fmt.Println(line.Text)}…
引用kostix的答案:
在现实生活中,文件可能会被截断,替换或重命名(因为logrotate之类的工具应该这样做)。
如果文件被截断,它将自动重新打开。为了支持重新打开重命名的文件(由于logrotate等),可以设置Config.ReOpen,即:
t, err := tail.TailFile("/var/log/nginx.log", tail.Config{ Follow: true, ReOpen: true})for line := range t.Lines { fmt.Println(line.Text)}Config.ReOpen类似于
tail -F(大写F):
-F The -F option implies the -f option, but tail will also check to see if the file being followed has been renamed or rotated. The file is closed and reopened when tail detects that the filename being read from has a new inode number. The -F option is ignored if reading from standard input rather than a file.



