2021-12-28 00:49:57 +08:00

76 lines
1.5 KiB
Go

package logging
import (
"github.com/sirupsen/logrus"
)
const (
defaultTimestampFormat = "2006-01-02 15:04:05.000000"
defaultLoggerLevel = logrus.DebugLevel
)
var DefaultConfig = defaultConfig()
func defaultConfig() *Config {
return &Config{
Level: defaultLoggerLevel.String(),
TimestampFormat: defaultTimestampFormat,
ReportCaller: true,
}
}
type Config struct {
Level string
TimestampFormat string `mapstructure:"timestamp_format"`
ReportCaller bool `mapstructure:"report_caller"`
}
func (cfg Config) GetLevel() logrus.Level {
l, err := logrus.ParseLevel(cfg.Level)
if err != nil {
logrus.
WithError(err).
Errorf("parse logger level failed with: %s", cfg.Level)
return defaultLoggerLevel
}
return l
}
func (cfg Config) GetTimestampFormat() string {
if cfg.TimestampFormat != "" {
return cfg.TimestampFormat
}
return defaultTimestampFormat
}
func Init() {
InitLogger(DefaultConfig)
}
func InitLogger(cfg *Config, hooks ...logrus.Hook) {
logrus.SetLevel(cfg.GetLevel())
logrus.SetReportCaller(cfg.ReportCaller)
formatter := logrus.JSONFormatter{
PrettyPrint: true,
TimestampFormat: cfg.GetTimestampFormat(),
}
logrus.SetFormatter(&formatter)
for _, hook := range hooks {
logrus.AddHook(hook)
}
}
func New() logrus.FieldLogger {
return logrus.StandardLogger()
}
func WithScope(scope string) logrus.FieldLogger {
return logrus.WithField("scope", scope)
}
func AddHook(hook logrus.Hook) {
logrus.AddHook(hook)
}