dongnue4923 2012-04-13 05:35
浏览 30
已采纳

在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.

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.

  • 写回答

5条回答 默认 最新

  • doq8211 2013-03-10 23:08
    关注

    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)
    }
    

    ...

    Quoting kostix's answer:

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

    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 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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器