Go app framework
This commit is contained in:
72
pkg/logging/logging.go
Normal file
72
pkg/logging/logging.go
Normal file
@ -0,0 +1,72 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
|
||||
)
|
||||
|
||||
func MustInitLogging(ctx context.Context) context.Context {
|
||||
cfg := config.MustFromCtx(ctx)
|
||||
|
||||
logger, err := configureLogger(cfg.Logging)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return logger.WithContext(ctx)
|
||||
}
|
||||
|
||||
func configureLogger(cfg *config.LogConfig) (*zerolog.Logger, error) {
|
||||
setTimeFormat(cfg.TimeFormat)
|
||||
|
||||
// Default JSON logger
|
||||
logger := zerolog.New(os.Stderr)
|
||||
if cfg.TimeFormat != config.TimeFormatOff {
|
||||
logger = logger.With().Timestamp().Logger()
|
||||
}
|
||||
|
||||
// Pretty console logger
|
||||
if cfg.Format == config.LogFormatConsole {
|
||||
consoleWriter := zerolog.ConsoleWriter{
|
||||
Out: os.Stderr,
|
||||
TimeFormat: zerolog.TimeFieldFormat,
|
||||
}
|
||||
if cfg.TimeFormat == config.TimeFormatOff {
|
||||
consoleWriter.FormatTimestamp = func(_ interface{}) string {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
logger = log.Output(consoleWriter)
|
||||
}
|
||||
|
||||
level, err := zerolog.ParseLevel(cfg.Level)
|
||||
if err != nil {
|
||||
level = zerolog.InfoLevel
|
||||
}
|
||||
|
||||
logger = logger.Level(level)
|
||||
zerolog.SetGlobalLevel(level)
|
||||
|
||||
return &logger, err
|
||||
}
|
||||
|
||||
func setTimeFormat(format config.TimeFormat) {
|
||||
switch format {
|
||||
case config.TimeFormatShort:
|
||||
zerolog.TimeFieldFormat = time.Kitchen
|
||||
case config.TimeFormatUnix:
|
||||
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
||||
case config.TimeFormatLong:
|
||||
zerolog.TimeFieldFormat = time.DateTime
|
||||
case config.TimeFormatRFC3339:
|
||||
zerolog.TimeFieldFormat = time.RFC3339
|
||||
case config.TimeFormatOff:
|
||||
zerolog.TimeFieldFormat = ""
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user