Send log to Rsyslog server with go

Viewed 332

I write a code to send log to rsyslog server on ubuntu, the code has below content. In the file ryslogd.conf I have configured local7.* /var/log/test.log.*But when running, the log is not written to the test.log *

package main
import (
        "errors"
        "fmt"
        "log/syslog"
        "os"
        "path/filepath"
)

func main() {
        programName := filepath.Base(os.Args[0])
        fmt.Println(programName)
        syslog_pointer, err := syslog.Dial("udp", "localhost:514", syslog.LOG_WARNING|syslog.LOG_LOCAL7, "test")
        if err != nil {
                err_exception := errors.New("Can't connect to syslog server localhost:514")
                fmt.Println(err_exception)
                os.Exit(1)
        } else {
                syslog_pointer.Emerg("This is log test")
        }
}

I want the log line: this is test log to be written to the file /var/log/test.log

1 Answers

Local logging is typically via a Unix socket. UDP logging typically needs to be explicitly enabled for the Syslog server.

Creating the syslog.Writer via syslog.New will attempt to connect via common Unix sockets first, then attempt UDP via localhost:

package main

import (
    "log"
    "log/syslog"
)

func main() {
    s, err := syslog.New(syslog.LOG_WARNING|syslog.LOG_LOCAL7, "test")
    if err != nil {
        log.Fatal(err)
    }
    
    s.Emerg("log test")
}
Related