gitee.com/quant1x/engine@v1.8.4/tools/tail.go (about)

     1  package tools
     2  
     3  import (
     4  	"fmt"
     5  	"gitee.com/quant1x/gox/util/homedir"
     6  	"gitee.com/quant1x/pkg/tools/tail"
     7  	"strings"
     8  )
     9  
    10  // TailFile 跟踪文件更新 tail -f
    11  func TailFile(filename string, config tail.Config, done chan bool) {
    12  	defer func() { done <- true }()
    13  	filename, _ = homedir.Expand(filename)
    14  	t, err := tail.TailFile(filename, config)
    15  	if err != nil {
    16  		fmt.Println(err)
    17  		return
    18  	}
    19  	for line := range t.Lines {
    20  		fmt.Println(line.Text)
    21  	}
    22  	err = t.Wait()
    23  	if err != nil {
    24  		fmt.Println(err)
    25  	}
    26  }
    27  
    28  // TailFileWithNumber 查看最后n行数据
    29  func TailFileWithNumber(filename string, config tail.Config, n int) {
    30  	filename, _ = homedir.Expand(filename)
    31  	t, err := tail.TailFile(filename, config)
    32  	if err != nil {
    33  		fmt.Println(err)
    34  		return
    35  	}
    36  
    37  	builder := strings.Builder{}
    38  	for line := range t.Lines {
    39  		builder.WriteString(line.Text + "\n")
    40  	}
    41  	arr := strings.Split(builder.String(), "\n")
    42  	total := len(arr)
    43  	pos := n + 1
    44  	if n >= total {
    45  		n = total
    46  	}
    47  	//var lines []string
    48  	for i, v := range arr {
    49  		if i < total-pos {
    50  			continue
    51  		}
    52  		fmt.Printf(v + "\n")
    53  	}
    54  }