英文:
Get new lines of syslog to my custom program(daemon)
问题
我需要在我的C(或Golang)程序中获取新的syslog行,当它被写入时。
该程序作为Linux守护进程运行,并且将始终在内存中。
这里,这张图片解释了我所需要的完整代码流程。
运行流程
请检查并指导我如何操作。
谢谢,
英文:
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
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 (
"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{})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论