Consider the following as a hacked example.
I am not sure if tail.Tail
closed tail.Tail
if you call Stop
or StopAtEOF
and then Cleanup
.
It is also necessary to clarify aspects of concurrency. Gorutins should be gracefully closed.
Import:
- github.com/fsnotify/fsnotify
- github.com/hpcloud/tail
The function of checking new files:
func newFileCheck(dir string) (newFileAlert <-chan string, err error) { watcher, err := fsnotify.NewWatcher() if err != nil { return } err = watcher.Add(dir) if err != nil { return } newFileAlertSender := make(chan string) newFileAlert = newFileAlertSender go func() { for { select { case ev.Op := <-watcher.Events: log.Println("Event : ", ev) if ev == fsnotify.Create { newFileAlertSender <- ev.Name } case err := <-watcher.Errors: log.Println("Watcher Error : ", err) } } }() return }
Function for tail file:
func tailFile(dir, newFileName string, cfg tail.Config, stop <-chan struct{}) { t, err := tail.TailFile(dir+newFileName, cfg) if err != nil { log.Fatalln("TailFile failed - ", err) } for line := range t.Lines { if strings.Contains(strings.ToLower(line.Text), "mfc") { fmt.Println("MFC located: ", line.Text) //sendEmail(line.Text) } select { case <-stop: t.StopAtEOF() default: } } t.Cleanup() }
The main:
func main() { dir := "/var/log/" currentTime := time.Now().Local() currentFileName := currentTime.Format("20060102") newFileName := currentFileName + "_1111.log.txt" newFileAlert, err := newFileCheck(dir) if err != nil { log.Fatalln("File watching failed - ", err) } stop := make(chan struct{}) cfg := tail.Config{Follow: true, ReOpen: true} go tailFile(dir, newFileName, cfg, stop) for fileName := range newFileAlert { stop <- struct{}{} go tailFile(dir, fileName, cfg, stop) } }
source share