Reading log files as they're updated in Go

前端 未结 5 1158
刺人心
刺人心 2020-12-14 14:29

I\'m trying to parse some log files as they\'re being written in Go but I\'m not sure how I would accomplish this without rereading the file again and again while checking f

5条回答
  •  攒了一身酷
    2020-12-14 15:04

    There are many ways to do this. In modern POSIX based Operating Systems, one can use the inotify interface to do this.

    One can use this package: https://github.com/fsnotify/fsnotify

    Sample code:

    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        log.Fatal(err)
    }
    
    done := make(chan bool)
    
    err = watcher.Add(fileName)
    if err != nil {
        log.Fatal(err)
    }
    for {
        select {
        case event := <-watcher.Events:
            if event.Op&fsnotify.Write == fsnotify.Write {
                log.Println("modified file:", event.Name)
    
            }
    }
    

    Hope this helps!

提交回复
热议问题