天天看點

Golang實作tail追蹤顯示檔案内容

背景

使用golang實作追蹤某一持續增長的檔案(例如:日志檔案) 讀取内容并分析

追蹤檔案内容 功能與tail一緻 這裡我們可以使用github.com/hpcloud/tail包

位址:https://github.com/hpcloud/tail

方法

在該包的說明中簡潔明了地展示了如何使用

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

使用上述方法可以列印出檔案的内容并跟蹤

但如果我們隻需要最新的内容 那麼就需要了解一下這個Config需要怎麼設定

// Config is used to specify how a file must be tailed.
type Config struct {
	// File-specifc
	Location    *SeekInfo //追蹤開始的位置設定
	ReOpen      bool      //true:檔案被删,阻塞并等待建立此檔案(同tail -F) false:檔案被删,程式結束  
	MustExist   bool      //true:檔案不存在即退出 false:檔案不存在即等待
	Poll        bool      // Poll for file changes instead of using inotify
	Pipe        bool      // Is a named pipe (mkfifo)
	RateLimiter *ratelimiter.LeakyBucket

	// Generic IO
	Follow      bool //true:一直監聽(同tail -f) false:一次後即結束
	MaxLineSize int  //若非零則為每行最大長度 超過該長度則分成多行

	// Logger, when nil, is set to tail.DefaultLogger
	// To disable logging: set field to tail.DiscardingLogger
	Logger logger
}

// SeekInfo represents arguments to `os.Seek`
type SeekInfo struct {
	Offset int64	//偏移
	Whence int 	// os.SEEK_SET:開始位置/os.SEEK_CUR:目前位置(首次使用與前面一緻)/os.SEEK_END:結尾位置
}
           

如果我們隻需要監視最新的檔案内容 那麼需要将location設定到檔案末尾

//設定seek 到文末
seek := &tail.SeekInfo{}
seek.Offset = 0
seek.Whence = os.SEEK_END
//設定配置
config := tail.Config{}
config.Follow = true
config.Location = seek
t, err := tail.TailFile("/var/log/nginx.log", config)
if err != nil {
	Error(err)
	return
}
for line := range t.Lines {
	fmt.Println(line.Text)
}
           

如上我們就可以隻讀取新增的檔案内容了