2020-07-10 14:17:51 +00:00
|
|
|
package logger
|
|
|
|
|
|
|
|
import (
|
2020-07-24 13:54:03 +00:00
|
|
|
"errors"
|
2020-07-10 14:17:51 +00:00
|
|
|
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"go.uber.org/zap/zapcore"
|
|
|
|
)
|
|
|
|
|
2022-04-21 11:28:05 +00:00
|
|
|
// Logger represents a component
|
2020-07-24 13:54:03 +00:00
|
|
|
// for writing messages to log.
|
2022-09-28 07:41:01 +00:00
|
|
|
type Logger struct {
|
|
|
|
*zap.Logger
|
|
|
|
lvl zap.AtomicLevel
|
|
|
|
}
|
2020-07-24 13:54:03 +00:00
|
|
|
|
2021-05-11 08:54:59 +00:00
|
|
|
// Prm groups Logger's parameters.
|
|
|
|
type Prm struct {
|
|
|
|
level zapcore.Level
|
|
|
|
}
|
|
|
|
|
2020-07-24 13:54:03 +00:00
|
|
|
// ErrNilLogger is returned by functions that
|
2022-04-21 11:28:05 +00:00
|
|
|
// expect a non-nil Logger but received nil.
|
2020-07-24 13:54:03 +00:00
|
|
|
var ErrNilLogger = errors.New("logger is nil")
|
2020-07-10 14:17:51 +00:00
|
|
|
|
2022-04-21 11:28:05 +00:00
|
|
|
// SetLevelString sets the minimum logging level.
|
2021-05-11 08:54:59 +00:00
|
|
|
//
|
|
|
|
// Returns error of s is not a string representation of zap.Level
|
|
|
|
// value (see zapcore.Level docs).
|
|
|
|
func (p *Prm) SetLevelString(s string) error {
|
|
|
|
return p.level.UnmarshalText([]byte(s))
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewLogger constructs a new zap logger instance.
|
|
|
|
//
|
|
|
|
// Logger is built from production logging configuration with:
|
2022-08-15 16:20:20 +00:00
|
|
|
// - parameterized level;
|
|
|
|
// - console encoding;
|
|
|
|
// - ISO8601 time encoding.
|
2021-05-11 08:54:59 +00:00
|
|
|
//
|
|
|
|
// Logger records a stack trace for all messages at or above fatal level.
|
|
|
|
func NewLogger(prm Prm) (*Logger, error) {
|
2022-09-28 07:41:01 +00:00
|
|
|
lvl := zap.NewAtomicLevelAt(prm.level)
|
|
|
|
|
2020-07-10 14:17:51 +00:00
|
|
|
c := zap.NewProductionConfig()
|
2022-09-28 07:41:01 +00:00
|
|
|
c.Level = lvl
|
2021-05-11 08:17:45 +00:00
|
|
|
c.Encoding = "console"
|
2020-07-10 14:17:51 +00:00
|
|
|
c.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
|
|
|
|
2022-09-28 07:41:01 +00:00
|
|
|
l, err := c.Build(
|
2021-05-11 08:17:45 +00:00
|
|
|
zap.AddStacktrace(zap.NewAtomicLevelAt(zap.FatalLevel)),
|
|
|
|
)
|
2022-09-28 07:41:01 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &Logger{Logger: l, lvl: lvl}, nil
|
2020-07-10 14:17:51 +00:00
|
|
|
}
|