github.com/dayvar14/tail@v0.0.0-20240222011302-f530c4fa0c9f/examples/02-closeAndReopen/main.go (about) 1 // Tail a file, print its contents, close it and reopen it. 2 // 3 // In this example you can add lines to the syslog log by using the logger 4 // command. Exit with Ctrl+C. 5 package main 6 7 import ( 8 "fmt" 9 "time" 10 11 "github.com/nxadm/tail" 12 ) 13 14 var logFile = "/var/log/syslog" 15 16 func main() { 17 // Open the file 18 t, err := tail.TailFile(logFile, tail.Config{Follow: true}) 19 if err != nil { 20 panic(err) 21 } 22 23 go func() { 24 for line := range t.Lines { 25 fmt.Println(line.Text) 26 } 27 }() 28 29 time.Sleep(time.Second * 5) // Give time to the go routine to print stuff 30 fmt.Println("Closing the logfile " + logFile) 31 err = t.Stop() 32 if err != nil { 33 fmt.Printf("ERROR: %s\n", err) 34 } 35 fmt.Println("Closed the logfile " + logFile) 36 // If you plan to reread the same file, do not call Cleanup() as inotify/Linux will get confused. 37 // As the documentation states: "This function is meant to be invoked from a process's exit handler". 38 //t.Cleanup() 39 40 // Reopen the file and print it 41 t, err = tail.TailFile(logFile, tail.Config{Follow: true}) 42 if err != nil { 43 panic(err) 44 } 45 defer t.Cleanup() 46 47 for line := range t.Lines { 48 fmt.Println(line.Text) 49 } 50 }