tail读取文件

go get github.com/nxadm/tail/...

go get github.com/hpcloud/tail/...因为依赖包改了地址而这里没改,所以直接get会出现问题,使用上面这个作为替代
package main

import (
    "fmt"
    "time"

    "github.com/nxadm/tail"
)

func main() {

    filename := "./text.txt"
    config := tail.Config{
        ReOpen:    true, //当出现轮转切割的时候,这两个参数会去追踪新的文件
        Follow:    true,
        Location:  &tail.SeekInfo{Offset: 0, Whence: 2}, //从哪开始
        MustExist: false,//允许文件不存在
        Poll:      true, //轮询
    }

    tails, err := tail.TailFile(filename, config)
    if err != nil {
        fmt.Println("error happens:", err)
    }
    var msg *tail.Line
    var flag bool

    for {
        msg, flag = <-tails.Lines
        if !flag {
            fmt.Println("tail can read anything from ", tails.Filename)
            time.After(1 * time.Second)
        } else {
            fmt.Println(msg.Text)
        }
    }
}

标签: none

评论已关闭