solana_exporter/pkg/slog/logger.go

57 lines
1.1 KiB
Go
Raw Normal View History

2024-10-25 01:10:21 -07:00
package slog
import (
2024-10-25 02:50:16 -07:00
"fmt"
2024-10-25 01:10:21 -07:00
"go.uber.org/zap"
2024-10-25 01:38:15 -07:00
"go.uber.org/zap/zapcore"
2024-10-25 02:50:16 -07:00
"os"
"strings"
2024-10-25 01:10:21 -07:00
)
var log *zap.SugaredLogger
2024-10-28 09:19:07 -07:00
// Init initializes the logger
func Init() {
2024-10-25 01:38:15 -07:00
config := zap.NewProductionConfig()
2024-10-25 02:50:16 -07:00
// configure:
2024-10-25 01:38:15 -07:00
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
2024-10-25 02:50:16 -07:00
config.Level = zap.NewAtomicLevelAt(getEnvLogLevel())
2024-10-25 01:38:15 -07:00
2024-10-25 02:50:16 -07:00
logger, err := config.Build()
if err != nil {
panic(fmt.Errorf("error initializing logger: %v", err))
}
2024-10-25 01:10:21 -07:00
log = logger.Sugar()
}
// Get returns the global logger instance
func Get() *zap.SugaredLogger {
return log
}
// Sync flushes any buffered log entries
func Sync() error {
return log.Sync()
}
2024-10-25 02:50:16 -07:00
func getEnvLogLevel() zapcore.Level {
level, ok := os.LookupEnv("LOG_LEVEL")
if !ok {
return zapcore.InfoLevel
}
switch strings.ToLower(level) {
case "debug":
return zapcore.DebugLevel
case "info":
return zapcore.InfoLevel
case "warn":
return zapcore.WarnLevel
case "error":
return zapcore.ErrorLevel
default:
2024-10-28 09:19:07 -07:00
fmt.Printf("Unrecognised 'LOG_LEVEL' environment variable '%s', using 'info'\n", level)
2024-10-25 02:50:16 -07:00
return zapcore.InfoLevel
}
}