1 Star 0 Fork 0

zhangjungang/beats

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
syslog_unix.go 2.21 KB
一键复制 编辑 原始数据 按行查看 历史
Andrew Kroh 提交于 2017-12-18 18:46 . Add log output to Windows Event Log
// +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
}
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zhangjungang/beats.git
git@gitee.com:zhangjungang/beats.git
zhangjungang
beats
beats
v6.2.3

搜索帮助