Go operation tail

Go operation tail


table of Contents

  1. Go operation tail

1. Go operation tail

1. tail

  1. The tail library produced by the HP team is often used for log collection

2. Download and install

go get github.com/hpcloud/tail

3. Go operation tail

package main

import (
	"fmt"
	"time"

	"github.com/hpcloud/tail"
)

// tailf的用法示例

func main() {
    
    
	fileName := "./my.log"
	config := tail.Config{
    
    
		ReOpen:    true,                                 // 重新打开
		Follow:    true,                                 // 是否跟随
		Location:  &tail.SeekInfo{
    
    Offset: 0, Whence: 2}, // 从文件的哪个地方开始读
		MustExist: false,                                // 文件不存在不报错
		Poll:      true,
	}
	tails, err := tail.TailFile(fileName, config) //开始跟踪文件。输出流是Tail.Lines的通道
	if err != nil {
    
    
		fmt.Println("tail file failed, err:", err)
		return
	}
	var (
		line *tail.Line
		ok   bool
	)
	for {
    
    
		line, ok = <-tails.Lines
		if !ok {
    
    
			fmt.Printf("tail file close reopen, filename:%s\n", tails.Filename)
			time.Sleep(time.Second)
			continue
		}
		fmt.Println("line:", line.Text)
	}
}

Guess you like

Origin blog.csdn.net/weixin_41910694/article/details/106764363