timetable-mgr/log/log.go

78 lines
1.5 KiB
Go
Raw Normal View History

2023-07-18 14:09:28 +01:00
package log
import (
2024-04-14 19:03:13 +01:00
"os"
2023-07-18 14:09:28 +01:00
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
2024-04-14 20:00:34 +01:00
// Use outside `package log`
2024-04-14 19:03:13 +01:00
// should be avoided.
var post *zap.Logger
2023-07-18 14:09:28 +01:00
// Initialises the logger
2024-04-14 20:00:34 +01:00
func InitLogger() {
2023-07-18 14:09:28 +01:00
var err error
2024-04-14 19:03:13 +01:00
mode := os.Getenv("runtime")
if mode == "" {
mode = "prod"
}
2023-07-18 14:09:28 +01:00
2024-04-14 20:00:34 +01:00
var level zapcore.Level
2024-04-14 19:03:13 +01:00
if mode == "debug" {
2024-04-14 20:00:34 +01:00
level = zap.DebugLevel
} else {
level = zap.InfoLevel
}
2024-04-14 19:03:13 +01:00
config := zap.NewDevelopmentConfig()
2024-04-14 21:20:17 +01:00
config.DisableStacktrace = true
2024-04-14 19:03:13 +01:00
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
2024-04-14 20:00:34 +01:00
config.Level = zap.NewAtomicLevelAt(level)
2024-04-14 19:03:13 +01:00
post, err = config.Build(zap.AddCallerSkip(1))
2023-07-18 14:09:28 +01:00
if err != nil {
panic("Failed to initialize logger: " + err.Error())
}
2024-04-14 19:03:13 +01:00
defer post.Sync()
2024-04-14 20:00:34 +01:00
Info("Logger initialised", zap.String("level", level.String()), zap.String("runtime", mode))
2024-04-14 19:03:13 +01:00
}
2024-04-14 20:00:34 +01:00
// Logs message at info level
2024-04-14 19:03:13 +01:00
func Info(msg string, fields ...zap.Field) {
post.Info(msg, fields...)
}
2024-04-14 20:00:34 +01:00
// Logs message at debug level
2024-04-14 19:03:13 +01:00
func Debug(msg string, fields ...zap.Field) {
post.Debug(msg, fields...)
}
2024-04-14 20:00:34 +01:00
// Logs message at warn level
2024-04-14 19:03:13 +01:00
func Warn(msg string, fields ...zap.Field) {
post.Warn(msg, fields...)
}
2024-04-14 20:00:34 +01:00
// Logs message at error level
2024-04-14 19:03:13 +01:00
func Error(msg string, fields ...zap.Field) {
post.Error(msg, fields...)
}
2024-04-14 20:00:34 +01:00
// Logs message at fatal level then call os.exit(1)
2024-04-14 19:03:13 +01:00
func Fatal(msg string, fields ...zap.Field) {
post.Fatal(msg, fields...)
}
2024-04-14 20:00:34 +01:00
// Logs message at panic level the panics
2024-04-14 19:03:13 +01:00
func Panic(msg string, fields ...zap.Field) {
post.Panic(msg, fields...)
2023-07-18 14:09:28 +01:00
}
2024-04-14 20:00:34 +01:00
// Flushes log messages
func Cleanup() {
Info("Flushing log messages")
post.Sync()
}