我正在尝试解析一些日志文件,因为它们是用Go语言编写的,但是我不确定在不进行检查更改的情况下一次又一次地重新读取该文件的情况下,如何实现这一点。
我希望能够读到EOF,等到下一行写完后再读到EOF,依此类推。感觉有点像tail -f。
tail -f
我已经编写了一个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):
Config.ReOpen
tail -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.