error-pages/internal/logger/logger.go

62 lines
1.4 KiB
Go
Raw Normal View History

2021-09-29 15:38:50 +00:00
// Package logger contains functions for a working with application logging.
package logger
import (
2023-01-29 10:54:56 +00:00
"errors"
2021-09-29 15:38:50 +00:00
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
2023-01-29 10:54:56 +00:00
// New creates new "zap" logger with a small customization.
func New(l Level, f Format) (*zap.Logger, error) {
2021-09-29 15:38:50 +00:00
var config zap.Config
2023-01-29 10:54:56 +00:00
switch f {
case ConsoleFormat:
2021-09-29 15:38:50 +00:00
config = zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeLevel = zapcore.LowercaseColorLevelEncoder
config.EncoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("15:04:05")
2023-01-29 10:54:56 +00:00
case JSONFormat:
config = zap.NewProductionConfig() // json encoder is used by default
default:
return nil, errors.New("unsupported logging format")
2021-09-29 15:38:50 +00:00
}
// default configuration for all encoders
config.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
config.Development = false
config.DisableStacktrace = true
config.DisableCaller = true
2023-01-29 10:54:56 +00:00
// enable additional features for debugging
if l <= DebugLevel {
2021-09-29 15:38:50 +00:00
config.Development = true
config.DisableStacktrace = false
config.DisableCaller = false
}
2023-01-29 10:54:56 +00:00
var zapLvl zapcore.Level
switch l { // convert level to zap.Level
case DebugLevel:
zapLvl = zap.DebugLevel
case InfoLevel:
zapLvl = zap.InfoLevel
case WarnLevel:
zapLvl = zap.WarnLevel
case ErrorLevel:
zapLvl = zap.ErrorLevel
case FatalLevel:
zapLvl = zap.FatalLevel
default:
return nil, errors.New("unsupported logging level")
2021-09-29 15:38:50 +00:00
}
2023-01-29 10:54:56 +00:00
config.Level = zap.NewAtomicLevelAt(zapLvl)
2021-09-29 15:38:50 +00:00
return config.Build()
}