go读取日志tailf

go读取日志tailf

tailf

Go语言中读取日志使用第三方库:github.com/hpcloud/tail

下载及安装

go get github.com/hpcloud/tail

Tail结构体

type Tail struct {
    Filename string
    Lines    chan *Line
    Config

    tomb.Tomb // provides: Done, Kill, Dying
    // contains filtered or unexported fields
}

func TailFile函数

func TailFile(filename string, config Config) (*Tail, error)

TailFile begins 传入参数:日志文件的路径和配置文件,返回一个指向Tail结构体对象的指针。

Config结构体

type Config struct {
    // File-specifc
    Location    *SeekInfo // Seek to this location before tailing
    ReOpen      bool      // Reopen recreated files (tail -F)
    MustExist   bool      // Fail early if the file does not exist
    Poll        bool      // Poll for file changes instead of using inotify
    Pipe        bool      // Is a named pipe (mkfifo)
    RateLimiter *ratelimiter.LeakyBucket

    // Generic IO
    Follow      bool // Continue looking for new lines (tail -f)
    MaxLineSize int  // If non-zero, split longer lines into multiple lines

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

Config 用来定义文件被读取的方式。

Tail结构体中最重要的是Lines字段,他是存储Line指针来的一个通道。

Line的数据结构为:

Line结构体

type Line struct {
    Text string
    Time time.Time
    Err  error // Error from tail
}

这个结构体是用来存储读取的信息。

  1. 首先初始化配置结构体config
  2. 调用TailFile函数,并传入文件路径和config,返回有个tail的结构体,tail结构体的Lines字段封装了拿到的信息
  3. 遍历tail.Lnes字段,取出信息(注意这里要循环的取,因为tail可以实现实时监控)

读取日志

package main

/*
@author RandySun
@create 2021-09-11-14:46
*/

import (
	"fmt"
	"github.com/hpcloud/tail"
	"time"
)
// tail demo
func main() {
	fileName := `G:\goproject\go\logAgent\demo\randy.log`
	config := tail.Config{
		ReOpen:    true, // 打开文件
		Follow:    true, // 文件切割自动重新打开
		Location:  &tail.SeekInfo{Offset: 0, Whence: 2}, // Location读取文件的位置, Whence更加系统选择参数
		MustExist: false, // 允许日志文件不存在
		Poll:      true, // 轮询
	}
	// 打开文件读取日志
	tails, err := tail.TailFile(fileName, config)
	if err != nil {
		fmt.Println("tail file failed, err:", err)
		return
	}
	// 开始读取数据
	var (
		msg *tail.Line
		ok  bool
	)
	for {
		msg, ok = <-tails.Lines
		if !ok {
			fmt.Printf("tail file close reopen, filename:%s\n", tails.Filename)
			time.Sleep(time.Second) // 读取出错停止一秒
			continue
		}
		fmt.Println("msg:", msg.Text)
	}
}

读取日志:

image-20210911151310087

image-20210911151239167

image-20210911171022314

posted @ 2021-12-11 16:49  RandySun  阅读(491)  评论(0编辑  收藏  举报