golang tail
1 package main 2 3 import ( 4 "fmt" 5 "os" 6 "strconv" 7 "time" 8 9 "github.com/hpcloud/tail" 10 ) 11 12 func main() { 13 // 新启动一个协程一直往文件中写入 14 go writeSteam() 15 16 fileName := "./my.log" 17 tailfs, err := tail.TailFile(fileName, tail.Config{ 18 ReOpen: true, // 文件被移除或被打包,需要重新打开 19 Follow: true, // 实时跟踪 20 Location: &tail.SeekInfo{Offset: 0, Whence: 2}, // 如果程序出现异常,保存上次读取的位置,避免重新读取。 21 MustExist: false, // 如果文件不存在,是否推出程序,false是不退出 22 Poll: true, 23 }) 24 25 if err != nil { 26 fmt.Println("tailf failed, err:", err) 27 return 28 } 29 30 var msg *tail.Line 31 var ok bool 32 33 for true { 34 msg, ok = <-tailfs.Lines 35 // ok 是判断管道是否被关闭,如果关闭就是文件被重置了,需要重新读取新的管道 36 37 if !ok { 38 fmt.Println("tailf fail close reopen, fileName:", fileName) 39 continue 40 } 41 fmt.Println("text:", msg.Text) 42 } 43 44 fmt.Println("tail end") 45 } 46 47 func writeSteam() { 48 f, err := os.OpenFile("./my.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644) 49 if err != nil { 50 fmt.Println("open file is failed, err: ", err) 51 } 52 53 for i := 0; i < 100; i++ { 54 f.WriteString("write value " + strconv.Itoa(i) + "\n") 55 time.Sleep(2 * time.Second) 56 } 57 }