在创建新文件时,Golang会替换以前打开的文件

Spl*_*did 6 go

好的,我正在监视某个文件并对该文件进行一些tail -f分析.但是,另一个应用程序具有特定的逻辑,它将在下一个日期甚至之前创建一个新文件.

我正在寻找一种方法来检测新创建的文件(主机是linux机器),然后不重新启动我当前的go服务来开始拖尾新创建的文件.

这是我当前拖尾"当前文件"的逻辑:

func main(){

    currentTime := time.Now().Local()
    currentFileName := strings.Replace(currentTime.Format("2006-01-02"), "-","",2)
    newFileName := currentFileName + "_1111.log.txt"

    //using github.com/hpcloud/tail for tail
    t, err := tail.TailFile("/var/log/"+newFileName, tail.Config{Follow: true, ReOpen: true})
    for line := range t.Lines {
        //fmt.Println("Line is:", line.Text)

        //check do we have error inside new line
        if strings.Contains(strings.ToLower(line.Text), "mfc"){
            fmt.Println("MFC located: ", line.Text)

            //now send e-mail to all interested parties
            //sendEmail(line.Text)
        }

    }

    fmt.Println(err)
}
Run Code Online (Sandbox Code Playgroud)

当前文件而不是20161219_1111.log可以是20161219_2222.log或类似,并在第二天从20161220_1111.log等开始.

任何提示都是受欢迎的.

sim*_*xia 3

尝试一下github.com/fsnotify/fsnotify

一个简单的例子:

func newFileCheck() (newFilename chan string, err error) {
    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        // do some log
        return
    }

    err = watcher.Watch("testDir")
    if err != nil {
        // do some log
        return
    }

    newFilename = make(chan string)

    // Process events
    go func() {
        for {
            select {
            case ev := <-watcher.Event:
                log.Println("event:", ev)
                newFilename <- ev.Name // Relative path to the file
            case err := <-watcher.Error:
                log.Println("error:", err)
            }
        }
    }()

    return
}

func yourApp() {

    newFilenameChan, err := newFileCheck()
    if err != nil {
        // err check
    }


    go func() {
        for {
            select {
            case name := <-newFilenameChan:
                // close the old one and read new file
            }
        }
    }()
}
Run Code Online (Sandbox Code Playgroud)

更多详细信息,请参阅文档

  • 不要使用那个叉子。它特别指出积极的开发已转移到“github.com/fsnotify/fsnotify” (2认同)