Search code examples
cgodaemonsyslog

Get new lines of syslog to my custom program(daemon)


I need to get new lines of syslog to my c(or golang) program when it written.

The program run as linux daemon, and it will be always on memory.

Here, the picture explains full code flow that I needed.

Run Flows

1

Please check and guide me how. regards,


Solution

  • You can use nxadm/tail which mimics UNIX tail. If you need to have a finer grain of control, you can use inotify feature with fsnotify.

    Tail:

    package main
    
    import (
        "fmt"
    
        "github.com/nxadm/tail"
    )
    
    func main() {
        t, _ := tail.TailFile("/var/log", tail.Config{Follow: true})
    
        for line := range t.Lines {
            fmt.Println(line.Text)
        }
    
    }
    

    fsnotify:

    package main
    
    import (
        "log"
    
        "github.com/fsnotify/fsnotify"
    )
    
    func main() {
        watcher, err := fsnotify.NewWatcher()
        if err != nil {
            log.Fatal(err)
        }
        defer watcher.Close()
    
        go func() {
            for {
                select {
                case event, ok := <-watcher.Events:
                    if !ok {
                        return
                    }
                    log.Println("event:", event)
    
                case err, ok := <-watcher.Errors:
                    if !ok {
                        return
                    }
                    log.Println("error:", err)
                }
            }
        }()
    
        // Add a path.
        err = watcher.Add("/var/log")
        if err != nil {
            log.Fatal(err)
        }
    
        // Block main goroutine forever.
        <-make(chan struct{})
    }