天天看点

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

如上我们就可以只读取新增的文件内容了