logginghandler/vendor/github.com/rs/zerolog/syslog.go

81 lines
1.9 KiB
Go
Raw Normal View History

2020-10-13 15:26:40 +02:00
// +build !windows
// +build !binary_log
package zerolog
import (
"io"
)
2022-03-23 13:43:18 +01:00
// See http://cee.mitre.org/language/1.0-beta1/clt.html#syslog
// or https://www.rsyslog.com/json-elasticsearch/
const ceePrefix = "@cee:"
2020-10-13 15:26:40 +02:00
// SyslogWriter is an interface matching a syslog.Writer struct.
type SyslogWriter interface {
io.Writer
Debug(m string) error
Info(m string) error
Warning(m string) error
Err(m string) error
Emerg(m string) error
Crit(m string) error
}
type syslogWriter struct {
2022-03-23 13:43:18 +01:00
w SyslogWriter
prefix string
2020-10-13 15:26:40 +02:00
}
// SyslogLevelWriter wraps a SyslogWriter and call the right syslog level
// method matching the zerolog level.
func SyslogLevelWriter(w SyslogWriter) LevelWriter {
2022-03-23 13:43:18 +01:00
return syslogWriter{w, ""}
}
// SyslogCEEWriter wraps a SyslogWriter with a SyslogLevelWriter that adds a
// MITRE CEE prefix for JSON syslog entries, compatible with rsyslog
// and syslog-ng JSON logging support.
// See https://www.rsyslog.com/json-elasticsearch/
func SyslogCEEWriter(w SyslogWriter) LevelWriter {
return syslogWriter{w, ceePrefix}
2020-10-13 15:26:40 +02:00
}
func (sw syslogWriter) Write(p []byte) (n int, err error) {
2022-03-23 13:43:18 +01:00
var pn int
if sw.prefix != "" {
pn, err = sw.w.Write([]byte(sw.prefix))
if err != nil {
return pn, err
}
}
n, err = sw.w.Write(p)
return pn + n, err
2020-10-13 15:26:40 +02:00
}
// WriteLevel implements LevelWriter interface.
func (sw syslogWriter) WriteLevel(level Level, p []byte) (n int, err error) {
switch level {
case TraceLevel:
case DebugLevel:
2022-03-23 13:43:18 +01:00
err = sw.w.Debug(sw.prefix + string(p))
2020-10-13 15:26:40 +02:00
case InfoLevel:
2022-03-23 13:43:18 +01:00
err = sw.w.Info(sw.prefix + string(p))
2020-10-13 15:26:40 +02:00
case WarnLevel:
2022-03-23 13:43:18 +01:00
err = sw.w.Warning(sw.prefix + string(p))
2020-10-13 15:26:40 +02:00
case ErrorLevel:
2022-03-23 13:43:18 +01:00
err = sw.w.Err(sw.prefix + string(p))
2020-10-13 15:26:40 +02:00
case FatalLevel:
2022-03-23 13:43:18 +01:00
err = sw.w.Emerg(sw.prefix + string(p))
2020-10-13 15:26:40 +02:00
case PanicLevel:
2022-03-23 13:43:18 +01:00
err = sw.w.Crit(sw.prefix + string(p))
2020-10-13 15:26:40 +02:00
case NoLevel:
2022-03-23 13:43:18 +01:00
err = sw.w.Info(sw.prefix + string(p))
2020-10-13 15:26:40 +02:00
default:
panic("invalid level")
}
2022-03-23 13:43:18 +01:00
// Any CEE prefix is not part of the message, so we don't include its length
2020-10-13 15:26:40 +02:00
n = len(p)
return
}