2023-09-13 01:47:22 -04:00
|
|
|
package logger
|
|
|
|
|
|
|
|
import (
|
2024-04-24 01:01:22 -04:00
|
|
|
"os"
|
|
|
|
"strings"
|
2023-11-02 14:35:30 -04:00
|
|
|
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"go.uber.org/zap/zapcore"
|
2024-04-24 01:01:22 -04:00
|
|
|
"gopkg.in/natefinch/lumberjack.v2"
|
2023-09-13 01:47:22 -04:00
|
|
|
)
|
|
|
|
|
2024-04-24 01:01:22 -04:00
|
|
|
var Logger *zap.Logger
|
2023-09-13 01:47:22 -04:00
|
|
|
|
2024-04-24 01:01:22 -04:00
|
|
|
func InitLogger(logLevel string) {
|
|
|
|
logger := zap.New(buildZapCore(getZapLogLevel(logLevel)))
|
|
|
|
Logger = logger
|
2023-09-13 01:47:22 -04:00
|
|
|
}
|
|
|
|
|
2024-04-24 01:01:22 -04:00
|
|
|
func buildZapCore(logLevel zapcore.Level) zapcore.Core {
|
|
|
|
fileWriter := zapcore.AddSync(&lumberjack.Logger{
|
|
|
|
Filename: "logs/app.log",
|
|
|
|
MaxSize: 500,
|
|
|
|
MaxBackups: 3,
|
|
|
|
MaxAge: 28,
|
|
|
|
Compress: true,
|
|
|
|
})
|
|
|
|
consoleWriter := zapcore.AddSync(os.Stdout)
|
|
|
|
|
|
|
|
encoderConfig := zap.NewProductionEncoderConfig()
|
|
|
|
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
|
|
|
|
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
|
|
|
|
|
|
|
fileCore := zapcore.NewCore(zapcore.NewJSONEncoder(encoderConfig), fileWriter, logLevel)
|
|
|
|
consoleCore := zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), consoleWriter, logLevel)
|
|
|
|
combinedCore := zapcore.NewTee(fileCore, consoleCore)
|
|
|
|
return combinedCore
|
|
|
|
}
|
|
|
|
|
|
|
|
func getZapLogLevel(logLevel string) zapcore.Level {
|
|
|
|
switch strings.ToLower(logLevel) {
|
2023-09-13 01:47:22 -04:00
|
|
|
case "debug":
|
2024-04-24 01:01:22 -04:00
|
|
|
return zap.DebugLevel
|
2023-09-13 01:47:22 -04:00
|
|
|
case "warn":
|
2024-04-24 01:01:22 -04:00
|
|
|
return zap.WarnLevel
|
|
|
|
case "error":
|
|
|
|
return zap.ErrorLevel
|
2023-09-13 01:47:22 -04:00
|
|
|
case "info":
|
2024-04-24 01:01:22 -04:00
|
|
|
return zap.InfoLevel
|
2023-09-13 01:47:22 -04:00
|
|
|
default:
|
2024-04-24 01:01:22 -04:00
|
|
|
return zap.InfoLevel
|
2023-09-13 01:47:22 -04:00
|
|
|
}
|
|
|
|
}
|