Some checks failed
Build / Build Components (push) Has been cancelled
OCI image / Build container images (push) Has been cancelled
Pre-commit hooks / Pre-commit (push) Has been cancelled
Tests and linters / Lint (push) Has been cancelled
Tests and linters / Tests (push) Has been cancelled
Tests and linters / Tests with -race (push) Has been cancelled
Tests and linters / Staticcheck (push) Has been cancelled
Tests and linters / gopls check (push) Has been cancelled
Tests and linters / Run gofumpt (push) Has been cancelled
Vulncheck / Vulncheck (push) Has been cancelled
Change-Id: Ia2a79d6cb2a5eb263fb2e6db3f9cf9f2a7d57118 Signed-off-by: Anton Nikiforov <an.nikiforov@yadro.com>
242 lines
5.8 KiB
Go
242 lines
5.8 KiB
Go
package logger
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.frostfs.info/TrueCloudLab/zapjournald"
|
|
"github.com/ssgreg/journald"
|
|
"go.uber.org/zap"
|
|
"go.uber.org/zap/zapcore"
|
|
)
|
|
|
|
// Logger represents a component
|
|
// for writing messages to log.
|
|
type Logger struct {
|
|
z *zap.Logger
|
|
c zapcore.Core
|
|
t Tag
|
|
w bool
|
|
}
|
|
|
|
// Prm groups Logger's parameters.
|
|
// Successful passing non-nil parameters to the NewLogger (if returned
|
|
// error is nil) connects the parameters with the returned Logger.
|
|
// Parameters that have been connected to the Logger support its
|
|
// configuration changing.
|
|
//
|
|
// See also Logger.Reload, SetLevelString.
|
|
type Prm struct {
|
|
// support runtime rereading
|
|
level zapcore.Level
|
|
|
|
// SamplingHook hook for the zap.Logger
|
|
SamplingHook func(e zapcore.Entry, sd zapcore.SamplingDecision)
|
|
|
|
// do not support runtime rereading
|
|
dest string
|
|
|
|
// PrependTimestamp specifies whether to prepend a timestamp in the log
|
|
PrependTimestamp bool
|
|
|
|
// Options for zap.Logger
|
|
Options []zap.Option
|
|
|
|
// map of tag's bit masks to log level, overrides lvl
|
|
tl map[Tag]zapcore.Level
|
|
}
|
|
|
|
const (
|
|
DestinationUndefined = ""
|
|
DestinationStdout = "stdout"
|
|
DestinationJournald = "journald"
|
|
)
|
|
|
|
// SetLevelString sets the minimum logging level. Default is
|
|
// "info".
|
|
//
|
|
// Returns an error if s is not a string representation of a
|
|
// supporting logging level.
|
|
//
|
|
// Supports runtime rereading.
|
|
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
|
|
}
|
|
|
|
// SetTags parses list of tags with log level.
|
|
func (p *Prm) SetTags(tags [][]string) (err error) {
|
|
p.tl, err = parseTags(tags)
|
|
return err
|
|
}
|
|
|
|
// NewLogger constructs a new zap logger instance. Constructing with nil
|
|
// parameters is safe: default values will be used then.
|
|
// Passing non-nil parameters after a successful creation (non-error) allows
|
|
// runtime reconfiguration.
|
|
//
|
|
// Logger is built from production logging configuration with:
|
|
// - parameterized level;
|
|
// - console encoding;
|
|
// - ISO8601 time encoding.
|
|
//
|
|
// Logger records a stack trace for all messages at or above fatal level.
|
|
func NewLogger(prm Prm) (*Logger, error) {
|
|
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) {
|
|
c := zap.NewProductionConfig()
|
|
c.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
|
|
c.Encoding = "console"
|
|
if prm.SamplingHook != nil {
|
|
c.Sampling.Hook = prm.SamplingHook
|
|
}
|
|
|
|
if prm.PrependTimestamp {
|
|
c.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
|
} else {
|
|
c.EncoderConfig.TimeKey = ""
|
|
}
|
|
|
|
opts := []zap.Option{
|
|
zap.AddStacktrace(zap.NewAtomicLevelAt(zap.FatalLevel)),
|
|
zap.AddCallerSkip(1),
|
|
}
|
|
opts = append(opts, prm.Options...)
|
|
lZap, err := c.Build(opts...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
l := &Logger{z: lZap, c: lZap.Core()}
|
|
l = l.WithTag(TagMain)
|
|
|
|
return l, nil
|
|
}
|
|
|
|
func newJournaldLogger(prm Prm) (*Logger, error) {
|
|
c := zap.NewProductionConfig()
|
|
if prm.SamplingHook != nil {
|
|
c.Sampling.Hook = prm.SamplingHook
|
|
}
|
|
|
|
if prm.PrependTimestamp {
|
|
c.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
|
} else {
|
|
c.EncoderConfig.TimeKey = ""
|
|
}
|
|
|
|
encoder := zapjournald.NewPartialEncoder(zapcore.NewConsoleEncoder(c.EncoderConfig), zapjournald.SyslogFields)
|
|
|
|
core := zapjournald.NewCore(zap.NewAtomicLevelAt(zap.DebugLevel), encoder, &journald.Journal{}, zapjournald.SyslogFields)
|
|
coreWithContext := core.With([]zapcore.Field{
|
|
zapjournald.SyslogFacility(zapjournald.LogDaemon),
|
|
zapjournald.SyslogIdentifier(),
|
|
zapjournald.SyslogPid(),
|
|
})
|
|
|
|
var samplerOpts []zapcore.SamplerOption
|
|
if c.Sampling.Hook != nil {
|
|
samplerOpts = append(samplerOpts, zapcore.SamplerHook(c.Sampling.Hook))
|
|
}
|
|
samplingCore := zapcore.NewSamplerWithOptions(
|
|
coreWithContext,
|
|
time.Second,
|
|
c.Sampling.Initial,
|
|
c.Sampling.Thereafter,
|
|
samplerOpts...,
|
|
)
|
|
opts := []zap.Option{
|
|
zap.AddStacktrace(zap.NewAtomicLevelAt(zap.FatalLevel)),
|
|
zap.AddCallerSkip(1),
|
|
}
|
|
opts = append(opts, prm.Options...)
|
|
lZap := zap.New(samplingCore, opts...)
|
|
l := &Logger{z: lZap, c: lZap.Core()}
|
|
l = l.WithTag(TagMain)
|
|
|
|
return l, nil
|
|
}
|
|
|
|
// With create a child logger with new fields, don't affect the parent.
|
|
// Throws panic if tag is unset.
|
|
func (l *Logger) With(fields ...zap.Field) *Logger {
|
|
if l.t == 0 {
|
|
panic("tag is unset")
|
|
}
|
|
c := *l
|
|
c.z = l.z.With(fields...)
|
|
// With called under the logger
|
|
c.w = true
|
|
return &c
|
|
}
|
|
|
|
type core struct {
|
|
c zapcore.Core
|
|
l zap.AtomicLevel
|
|
}
|
|
|
|
func (c *core) Enabled(lvl zapcore.Level) bool {
|
|
return c.l.Enabled(lvl)
|
|
}
|
|
|
|
func (c *core) With(fields []zapcore.Field) zapcore.Core {
|
|
clone := *c
|
|
clone.c = clone.c.With(fields)
|
|
return &clone
|
|
}
|
|
|
|
func (c *core) Check(e zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
|
|
return c.c.Check(e, ce)
|
|
}
|
|
|
|
func (c *core) Write(e zapcore.Entry, fields []zapcore.Field) error {
|
|
return c.c.Write(e, fields)
|
|
}
|
|
|
|
func (c *core) Sync() error {
|
|
return c.c.Sync()
|
|
}
|
|
|
|
// WithTag is an equivalent of calling [NewLogger] with the same parameters for the current logger.
|
|
// Throws panic if provided unsupported tag.
|
|
func (l *Logger) WithTag(tag Tag) *Logger {
|
|
if tag == 0 || tag > Tag(len(_Tag_index)-1) {
|
|
panic("unsupported tag " + tag.String())
|
|
}
|
|
if l.w {
|
|
panic("unsupported operation for the logger's state")
|
|
}
|
|
c := *l
|
|
c.t = tag
|
|
c.z = l.z.WithOptions(zap.WrapCore(func(zapcore.Core) zapcore.Core {
|
|
return &core{
|
|
c: l.c.With([]zap.Field{zap.String("tag", tag.String())}),
|
|
l: tagToLogLevel[tag],
|
|
}
|
|
}))
|
|
return &c
|
|
}
|
|
|
|
func NewLoggerWrapper(z *zap.Logger) *Logger {
|
|
return &Logger{
|
|
z: z.WithOptions(zap.AddCallerSkip(1)),
|
|
t: TagMain,
|
|
}
|
|
}
|