在Go中更新日志文件 [英] Reading log files as they're updated in Go

查看:89
本文介绍了在Go中更新日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解析一些日志文件,因为它们是用Go编写的,但我不确定如何在检查更改时不重复读取文件的情况下完成此操作。

I'm trying to parse some log files as they're being written in Go but I'm not sure how I would accomplish this without rereading the file again and again while checking for changes.

我希望能够读取EOF,等到下一行被写入并再次读取到EOF,等等。感觉有点像 tail -f 的样子。

I'd like to be able to read to EOF, wait until the next line is written and read to EOF again, etc. It feels a bit like how tail -f looks.

推荐答案

我已经写了一个Go包 - github.com/ActiveState/tail - 做到这一点。

I have written a Go package -- github.com/ActiveState/tail -- to do exactly this.

t, err := tail.TailFile("/var/log/nginx.log", tail.Config{Follow: true})
for line := range t.Lines {
    fmt.Println(line.Text)
}

...

引用kostix的回答:

Quoting kostix's answer:


可能被截断,替换或重命名(因为这是什么工具像logrotate应该这样做)。

in real life files might be truncated, replaced or renamed (because that's what tools like logrotate are supposed to do).

如果文件被截断,它会自动重新打开。为了支持重新打开重命名文件(由于logrotate等),您可以设置 Config.ReOpen ,即:

If a file gets truncated, it will automatically be re-opened. To support re-opening renamed files (due to logrotate, etc.), you can set Config.ReOpen, viz.:

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 类似于尾部-F (大写字母F):

Config.ReOpen is analogous to tail -F (capital 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.

这篇关于在Go中更新日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆