log 下面还有个子库,也就是这个 syslog,据说这个库只在 Windows 上没有实现,看了下源码,应该确实只能工作在 *nix 系。这个库是用于连接到远程日志 daemon 进程,也就是把日志打到远程去,要打在本地当然也可以。
syslog.go
结构体和接口都很简单
// src/log/syslog/syslog.go ---- line 75// A Writer is a connection to a syslog server.type Writer struct {priority Prioritytag stringhostname stringnetwork stringraddr stringmu sync.Mutex // guards connconn serverConn}// This interface and the separate syslog_unix.go file exist for// Solaris support as implemented by gccgo. On Solaris you cannot// simply open a TCP connection to the syslog daemon. The gccgo// sources have a syslog_solaris.go file that implements unixSyslog to// return a type that satisfies this interface and simply calls the C// library syslog function.type serverConn interface {writeString(p Priority, hostname, tag, s, nl string) errorclose() error}type netConn struct {local boolconn net.Conn}
就简单看一下 connect 方法就行了
// src/log/syslog/syslog.go ---- line 146// connect makes a connection to the syslog server.// It must be called with w.mu held.func (w *Writer) connect() (err error) {if w.conn != nil {// ignore err from close, it makes sense to continue anywayw.conn.close()w.conn = nil}if w.network == "" {w.conn, err = unixSyslog()if w.hostname == "" {w.hostname = "localhost"}} else {var c net.Connc, err = net.Dial(w.network, w.raddr)if err == nil {w.conn = &netConn{conn: c}if w.hostname == "" {w.hostname = c.LocalAddr().String()}}}return}
如果没有指定远程服务器的时候,调用的是 unixSyslog 函数,那么这个函数又是干嘛的呢,它的定义在 syslog_unix.go 文件里
syslog_unix.go
// src/log/syslog/syslog_unix.go ---- line 14// unixSyslog opens a connection to the syslog daemon running on the// local machine using a Unix domain socket.func unixSyslog() (conn serverConn, err error) {logTypes := []string{"unixgram", "unix"}logPaths := []string{"/dev/log", "/var/run/syslog", "/var/run/log"}for _, network := range logTypes {for _, path := range logPaths {conn, err := net.Dial(network, path)if err == nil {return &netConn{conn: conn, local: true}, nil}}}return nil, errors.New("Unix syslog delivery error")}
是吧,所以说要在本地打日志的话,这种代码在 Win 上肯定是不行的呀。
不过有一说一,自己写了测试代码,在本地的时候,当 netword=”unixgram” path=”/dev/log” 连接成功了,没有返回 err,但是在对应目录找不到日志文件。看了网上别人的测试,日志都很正常。针对我?这里还得再看看,为啥打不出日志。
