golang tail

. 1  Package main
 2  
. 3  Import (
 . 4      "FMT"
 . 5      "OS"
 . 6      "StrConv"
 . 7      "Time"
 . 8  
. 9      "github.com/hpcloud/tail"
 10  )
 . 11  
12 is  FUNC main () {
 13 is      // new a co-promoter Cheng has been written to a file 
14      Go writeSteam ()
 15  
16      fileName: = "./my.log"
 . 17      tailfs, ERR: = tail.TailFile (fileName, {tail.Config
 18 is          REOPEN:     to true ,                                  //The file is removed or packed, need to reopen 
19          the Follow:     to true ,                                  // real-time tracking 
20          the Location: & tail.SeekInfo {Offset: 0, WHENCE: 2}, // if the program is abnormal, save the last reading position to avoid re-read. 
21          MustExist: false ,                                 // If the file does not exist, whether the introduction of the program, false is not quit 
22          Poll:       to true ,
 23      })
 24-  
25      IF ! ERR = nil {
 26          fmt.Println ( "failed The tailf, ERR:" , ERR )
 27          return 
28      }
 29 
30      var MSG * tail.Line
 31 is      var BOOL OK
 32  
33 is      for  to true {
 34 is          MSG, OK = <- tailfs.Lines
 35          // OK is determined whether the pipe is closed off if the file is to be reset, and need to be reread the new pipeline 
36  
37 [          IF ! OK {
 38 is              fmt.Println ( "Close Reopen tailf Fail, fileName:" , fileName)
 39              Continue 
40          }
 41 is          fmt.Println ( "text:" , msg.Text)
 42 is      }
 43 is  
44 is      FMT. println ( "tail End" )
 45  }
 46 is 
47 func writeSteam() {
48     f, err := os.OpenFile("./my.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
49     if err != nil {
50         fmt.Println("open file is failed, err: ", err)
51     }
52 
53     for i := 0; i < 100; i++ {
54         f.WriteString("write value " + strconv.Itoa(i) + "\n")
55         time.Sleep(2 * time.Second)
56     }
57 }

 

Guess you like

Origin www.cnblogs.com/chaselogs/p/11163025.html