forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
syslog_unix.go
99 lines (84 loc) · 2.21 KB
/
syslog_unix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// +build !windows,!nacl,!plan9
package logp
import (
"log/syslog"
"os"
"path/filepath"
"github.com/pkg/errors"
"go.uber.org/zap/zapcore"
)
type syslogCore struct {
zapcore.LevelEnabler
encoder zapcore.Encoder
writer *syslog.Writer
fields []zapcore.Field
}
// newSyslog returns a new Core that outputs to syslog.
func newSyslog(encoder zapcore.Encoder, enab zapcore.LevelEnabler) (zapcore.Core, error) {
// Initialize a syslog writer.
writer, err := syslog.New(syslog.LOG_ERR|syslog.LOG_LOCAL0, filepath.Base(os.Args[0]))
if err != nil {
return nil, errors.Wrap(err, "failed to get a syslog writer")
}
return &syslogCore{
LevelEnabler: enab,
encoder: encoder,
writer: writer,
}, nil
}
func (c *syslogCore) With(fields []zapcore.Field) zapcore.Core {
clone := c.Clone()
clone.fields = append(clone.fields, fields...)
return clone
}
func (c *syslogCore) Check(entry zapcore.Entry, checked *zapcore.CheckedEntry) *zapcore.CheckedEntry {
if c.Enabled(entry.Level) {
return checked.AddCore(entry, c)
}
return checked
}
func (c *syslogCore) Write(entry zapcore.Entry, fields []zapcore.Field) error {
buffer, err := c.encoder.EncodeEntry(entry, fields)
if err != nil {
return errors.Wrap(err, "failed to encode entry")
}
// Console encoder writes tabs which don't render nicely with syslog.
replaceTabsWithSpaces(buffer.Bytes(), 4)
msg := buffer.String()
switch entry.Level {
case zapcore.DebugLevel:
return c.writer.Debug(msg)
case zapcore.InfoLevel:
return c.writer.Info(msg)
case zapcore.WarnLevel:
return c.writer.Warning(msg)
case zapcore.ErrorLevel:
return c.writer.Err(msg)
case zapcore.DPanicLevel, zapcore.PanicLevel, zapcore.FatalLevel:
return c.writer.Crit(msg)
default:
return errors.Errorf("unhandled log level: %v", entry.Level)
}
}
func (c *syslogCore) Sync() error {
return nil
}
func (c *syslogCore) Clone() *syslogCore {
clone := *c
clone.encoder = c.encoder.Clone()
clone.fields = make([]zapcore.Field, len(c.fields), len(c.fields)+10)
copy(clone.fields, c.fields)
return &clone
}
func replaceTabsWithSpaces(b []byte, n int) {
var count = 0
for i, v := range b {
if v == '\t' {
b[i] = ' '
count++
if n >= 0 && count >= n {
return
}
}
}
}