[#736] logger: Add journald support

Signed-off-by: Dmitrii Stepanov <d.stepanov@yadro.com>
This commit is contained in:
Dmitrii Stepanov 2024-02-08 17:04:58 +03:00 committed by Evgenii Stratonikov
parent b36a453238
commit 962e5a9c19
11 changed files with 108 additions and 6 deletions

View file

@ -1,6 +1,10 @@
package logger
import (
"fmt"
"git.frostfs.info/TrueCloudLab/zapjournald"
"github.com/ssgreg/journald"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
@ -35,8 +39,15 @@ type Prm struct {
SamplingHook func(e zapcore.Entry, sd zapcore.SamplingDecision)
// do not support runtime rereading
dest string
}
const (
DestinationUndefined = ""
DestinationStdout = "stdout"
DestinationJournald = "journald"
)
// SetLevelString sets the minimum logging level. Default is
// "info".
//
@ -48,6 +59,16 @@ func (p *Prm) SetLevelString(s string) error {
return p.level.UnmarshalText([]byte(s))
}
func (p *Prm) SetDestination(d string) error {
if d != DestinationStdout && d != DestinationJournald {
return fmt.Errorf("invalid logger destination %s", d)
}
if p != nil {
p.dest = d
}
return nil
}
// Reload reloads configuration of a connected instance of the Logger.
// Returns ErrLoggerNotConnected if no connection has been performed.
// Returns any reconfiguration error from the Logger directly.
@ -79,7 +100,17 @@ func NewLogger(prm *Prm) (*Logger, error) {
if prm == nil {
prm = defaultPrm()
}
switch prm.dest {
case DestinationUndefined, DestinationStdout:
return newConsoleLogger(prm)
case DestinationJournald:
return newJournaldLogger(prm)
default:
return nil, fmt.Errorf("unknown destination %s", prm.dest)
}
}
func newConsoleLogger(prm *Prm) (*Logger, error) {
lvl := zap.NewAtomicLevelAt(prm.level)
c := zap.NewProductionConfig()
@ -103,6 +134,34 @@ func NewLogger(prm *Prm) (*Logger, error) {
return l, nil
}
func newJournaldLogger(prm *Prm) (*Logger, error) {
lvl := zap.NewAtomicLevelAt(prm.level)
c := zap.NewProductionConfig()
c.Level = lvl
c.Encoding = "console"
c.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
if prm.SamplingHook != nil {
c.Sampling.Hook = prm.SamplingHook
}
encoder := zapjournald.NewPartialEncoder(zapcore.NewConsoleEncoder(c.EncoderConfig), zapjournald.SyslogFields)
core := zapjournald.NewCore(zap.NewAtomicLevelAt(prm.level), encoder, &journald.Journal{}, zapjournald.SyslogFields)
coreWithContext := core.With([]zapcore.Field{
zapjournald.SyslogFacility(zapjournald.LogDaemon),
zapjournald.SyslogIdentifier(),
zapjournald.SyslogPid(),
})
lZap := zap.New(coreWithContext, zap.AddStacktrace(zap.NewAtomicLevelAt(zap.FatalLevel)))
l := &Logger{Logger: lZap, lvl: lvl}
prm._log = l
return l, nil
}
func (l *Logger) reload(prm Prm) error {
l.lvl.SetLevel(prm.level)
return nil