将syslog的新行发送到我的自定义程序(守护进程)中。

huangapple go评论71阅读模式
英文:

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

问题

我需要在我的C(或Golang)程序中获取新的syslog行,当它被写入时。

该程序作为Linux守护进程运行,并且将始终在内存中。

这里,这张图片解释了我所需要的完整代码流程。

运行流程

将syslog的新行发送到我的自定义程序(守护进程)中。

请检查并指导我如何操作。
谢谢,

英文:

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

将syslog的新行发送到我的自定义程序(守护进程)中。

Please check and guide me how.
regards,

答案1

得分: 0

你可以使用nxadm/tail来模拟UNIX的tail命令。如果你需要更精细的控制,可以使用fsnotify功能和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)
			}
		}
	}()

	// 添加一个路径。
	err = watcher.Add("/var/log")
	if err != nil {
		log.Fatal(err)
	}

	// 永久阻塞主goroutine。
	<-make(chan struct{})
}
英文:

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 (
	&quot;fmt&quot;

	&quot;github.com/nxadm/tail&quot;
)

func main() {
	t, _ := tail.TailFile(&quot;/var/log&quot;, tail.Config{Follow: true})

	for line := range t.Lines {
		fmt.Println(line.Text)
	}

}

fsnotify:

package main

import (
	&quot;log&quot;

	&quot;github.com/fsnotify/fsnotify&quot;
)

func main() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	go func() {
		for {
			select {
			case event, ok := &lt;-watcher.Events:
				if !ok {
					return
				}
				log.Println(&quot;event:&quot;, event)

			case err, ok := &lt;-watcher.Errors:
				if !ok {
					return
				}
				log.Println(&quot;error:&quot;, err)
			}
		}
	}()

	// Add a path.
	err = watcher.Add(&quot;/var/log&quot;)
	if err != nil {
		log.Fatal(err)
	}

	// Block main goroutine forever.
	&lt;-make(chan struct{})
}

huangapple
  • 本文由 发表于 2022年8月19日 12:36:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/73411883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定