syslog.go 7.15 KB
Newer Older
Yves Junqueira's avatar
Yves Junqueira committed
1 2 3 4
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5
// +build !windows,!nacl,!plan9
Russ Cox's avatar
Russ Cox committed
6

Yves Junqueira's avatar
Yves Junqueira committed
7 8 9
package syslog

import (
10
	"errors"
11 12 13 14
	"fmt"
	"log"
	"net"
	"os"
15 16
	"strings"
	"sync"
17
	"time"
Yves Junqueira's avatar
Yves Junqueira committed
18 19
)

20 21 22 23
// The Priority is a combination of the syslog facility and
// severity. For example, LOG_ALERT | LOG_FTP sends an alert severity
// message from the FTP facility. The default severity is LOG_EMERG;
// the default facility is LOG_KERN.
Yves Junqueira's avatar
Yves Junqueira committed
24 25
type Priority int

26 27 28
const severityMask = 0x07
const facilityMask = 0xf8

Yves Junqueira's avatar
Yves Junqueira committed
29
const (
30 31
	// Severity.

Yves Junqueira's avatar
Yves Junqueira committed
32 33
	// From /usr/include/sys/syslog.h.
	// These are the same on Linux, BSD, and OS X.
34 35 36 37 38 39 40 41
	LOG_EMERG Priority = iota
	LOG_ALERT
	LOG_CRIT
	LOG_ERR
	LOG_WARNING
	LOG_NOTICE
	LOG_INFO
	LOG_DEBUG
Yves Junqueira's avatar
Yves Junqueira committed
42 43
)

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
const (
	// Facility.

	// From /usr/include/sys/syslog.h.
	// These are the same up to LOG_FTP on Linux, BSD, and OS X.
	LOG_KERN Priority = iota << 3
	LOG_USER
	LOG_MAIL
	LOG_DAEMON
	LOG_AUTH
	LOG_SYSLOG
	LOG_LPR
	LOG_NEWS
	LOG_UUCP
	LOG_CRON
	LOG_AUTHPRIV
	LOG_FTP
	_ // unused
	_ // unused
	_ // unused
	_ // unused
	LOG_LOCAL0
	LOG_LOCAL1
	LOG_LOCAL2
	LOG_LOCAL3
	LOG_LOCAL4
	LOG_LOCAL5
	LOG_LOCAL6
	LOG_LOCAL7
)

Yves Junqueira's avatar
Yves Junqueira committed
75 76
// A Writer is a connection to a syslog server.
type Writer struct {
77
	priority Priority
78 79
	tag      string
	hostname string
80 81
	network  string
	raddr    string
82

83
	mu   sync.Mutex // guards conn
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
	conn serverConn
}

// This interface and the separate syslog_unix.go file exist for
// Solaris support as implemented by gccgo.  On Solaris you can not
// 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) error
	close() error
}

type netConn struct {
99 100
	local bool
	conn  net.Conn
Yves Junqueira's avatar
Yves Junqueira committed
101 102
}

103 104 105 106 107
// New establishes a new connection to the system log daemon.  Each
// write to the returned writer sends a log message with the given
// priority and prefix.
func New(priority Priority, tag string) (w *Writer, err error) {
	return Dial("", "", priority, tag)
Yves Junqueira's avatar
Yves Junqueira committed
108 109
}

110
// Dial establishes a connection to a log daemon by connecting to
111
// address raddr on the specified network.  Each write to the returned
112 113
// writer sends a log message with the given facility, severity and
// tag.
114
// If network is empty, Dial will connect to the local syslog server.
115
func Dial(network, raddr string, priority Priority, tag string) (*Writer, error) {
116 117
	if priority < 0 || priority > LOG_LOCAL7|LOG_DEBUG {
		return nil, errors.New("log/syslog: invalid priority")
Yves Junqueira's avatar
Yves Junqueira committed
118
	}
119 120 121 122 123 124

	if tag == "" {
		tag = os.Args[0]
	}
	hostname, _ := os.Hostname()

125 126 127 128 129 130
	w := &Writer{
		priority: priority,
		tag:      tag,
		hostname: hostname,
		network:  network,
		raddr:    raddr,
131
	}
132 133 134 135 136

	w.mu.Lock()
	defer w.mu.Unlock()

	err := w.connect()
137 138
	if err != nil {
		return nil, err
Yves Junqueira's avatar
Yves Junqueira committed
139
	}
140 141 142 143 144 145 146 147
	return w, err
}

// 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 anyway
148
		w.conn.close()
149 150
		w.conn = nil
	}
151

152 153 154 155 156 157 158 159 160
	if w.network == "" {
		w.conn, err = unixSyslog()
		if w.hostname == "" {
			w.hostname = "localhost"
		}
	} else {
		var c net.Conn
		c, err = net.Dial(w.network, w.raddr)
		if err == nil {
161
			w.conn = &netConn{conn: c}
162 163 164 165 166 167
			if w.hostname == "" {
				w.hostname = c.LocalAddr().String()
			}
		}
	}
	return
Yves Junqueira's avatar
Yves Junqueira committed
168 169 170
}

// Write sends a log message to the syslog daemon.
171
func (w *Writer) Write(b []byte) (int, error) {
172
	return w.writeAndRetry(w.priority, string(b))
Yves Junqueira's avatar
Yves Junqueira committed
173 174
}

175 176 177 178 179 180
// Close closes a connection to the syslog daemon.
func (w *Writer) Close() error {
	w.mu.Lock()
	defer w.mu.Unlock()

	if w.conn != nil {
181
		err := w.conn.close()
182 183 184 185 186
		w.conn = nil
		return err
	}
	return nil
}
Yves Junqueira's avatar
Yves Junqueira committed
187

188 189
// Emerg logs a message with severity LOG_EMERG, ignoring the severity
// passed to New.
190
func (w *Writer) Emerg(m string) (err error) {
191
	_, err = w.writeAndRetry(LOG_EMERG, m)
192
	return err
Yves Junqueira's avatar
Yves Junqueira committed
193
}
194

195 196
// Alert logs a message with severity LOG_ALERT, ignoring the severity
// passed to New.
197
func (w *Writer) Alert(m string) (err error) {
198
	_, err = w.writeAndRetry(LOG_ALERT, m)
199 200 201
	return err
}

202 203
// Crit logs a message with severity LOG_CRIT, ignoring the severity
// passed to New.
204
func (w *Writer) Crit(m string) (err error) {
205
	_, err = w.writeAndRetry(LOG_CRIT, m)
206
	return err
Yves Junqueira's avatar
Yves Junqueira committed
207
}
208

209 210
// Err logs a message with severity LOG_ERR, ignoring the severity
// passed to New.
211
func (w *Writer) Err(m string) (err error) {
212
	_, err = w.writeAndRetry(LOG_ERR, m)
213
	return err
Yves Junqueira's avatar
Yves Junqueira committed
214 215
}

216
// Warning logs a message with severity LOG_WARNING, ignoring the
217
// severity passed to New.
218
func (w *Writer) Warning(m string) (err error) {
219
	_, err = w.writeAndRetry(LOG_WARNING, m)
220
	return err
Yves Junqueira's avatar
Yves Junqueira committed
221 222
}

223 224
// Notice logs a message with severity LOG_NOTICE, ignoring the
// severity passed to New.
225
func (w *Writer) Notice(m string) (err error) {
226
	_, err = w.writeAndRetry(LOG_NOTICE, m)
227
	return err
Yves Junqueira's avatar
Yves Junqueira committed
228
}
229

230 231
// Info logs a message with severity LOG_INFO, ignoring the severity
// passed to New.
232
func (w *Writer) Info(m string) (err error) {
233
	_, err = w.writeAndRetry(LOG_INFO, m)
234
	return err
Yves Junqueira's avatar
Yves Junqueira committed
235
}
236

237 238
// Debug logs a message with severity LOG_DEBUG, ignoring the severity
// passed to New.
239
func (w *Writer) Debug(m string) (err error) {
240
	_, err = w.writeAndRetry(LOG_DEBUG, m)
241
	return err
Yves Junqueira's avatar
Yves Junqueira committed
242 243
}

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
func (w *Writer) writeAndRetry(p Priority, s string) (int, error) {
	pr := (w.priority & facilityMask) | (p & severityMask)

	w.mu.Lock()
	defer w.mu.Unlock()

	if w.conn != nil {
		if n, err := w.write(pr, s); err == nil {
			return n, err
		}
	}
	if err := w.connect(); err != nil {
		return 0, err
	}
	return w.write(pr, s)
259 260
}

261
// write generates and writes a syslog formatted string. The
262
// format is as follows: <PRI>TIMESTAMP HOSTNAME TAG[PID]: MSG
263 264
func (w *Writer) write(p Priority, msg string) (int, error) {
	// ensure it ends in a \n
265
	nl := ""
266
	if !strings.HasSuffix(msg, "\n") {
267 268
		nl = "\n"
	}
269

270
	err := w.conn.writeString(p, w.hostname, w.tag, msg, nl)
271 272 273 274 275 276
	if err != nil {
		return 0, err
	}
	// Note: return the length of the input, not the number of
	// bytes printed by Fprintf, because this must behave like
	// an io.Writer.
Rob Pike's avatar
Rob Pike committed
277
	return len(msg), nil
278 279
}

280 281 282 283 284 285 286 287 288 289 290
func (n *netConn) writeString(p Priority, hostname, tag, msg, nl string) error {
	if n.local {
		// Compared to the network form below, the changes are:
		//	1. Use time.Stamp instead of time.RFC3339.
		//	2. Drop the hostname field from the Fprintf.
		timestamp := time.Now().Format(time.Stamp)
		_, err := fmt.Fprintf(n.conn, "<%d>%s %s[%d]: %s%s",
			p, timestamp,
			tag, os.Getpid(), msg, nl)
		return err
	}
291 292 293 294 295 296 297
	timestamp := time.Now().Format(time.RFC3339)
	_, err := fmt.Fprintf(n.conn, "<%d>%s %s %s[%d]: %s%s",
		p, timestamp, hostname,
		tag, os.Getpid(), msg, nl)
	return err
}

298
func (n *netConn) close() error {
299 300 301
	return n.conn.Close()
}

302 303 304 305 306
// NewLogger creates a log.Logger whose output is written to
// the system log service with the specified priority. The logFlag
// argument is the flag set passed through to log.New to create
// the Logger.
func NewLogger(p Priority, logFlag int) (*log.Logger, error) {
307
	s, err := New(p, "")
Yves Junqueira's avatar
Yves Junqueira committed
308
	if err != nil {
309
		return nil, err
Yves Junqueira's avatar
Yves Junqueira committed
310
	}
311
	return log.New(s, "", logFlag), nil
Yves Junqueira's avatar
Yves Junqueira committed
312
}