12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package fslog
- import (
- "fmt"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
- "gopkg.in/natefinch/lumberjack.v2"
- "os"
- "path/filepath"
- "sync"
- )
- const (
- LoggerLevelInfo = "info"
- LoggerLevelError = "error"
- LoggerLevelDebug = "debug"
- LoggerLevelWarn = "Warn"
- )
- var LoggerLever = LoggerLevelDebug
- func chooseLoggerLever() zapcore.Level {
- switch LoggerLever {
- case LoggerLevelInfo:
- return zapcore.InfoLevel
- case LoggerLevelError:
- return zapcore.ErrorLevel
- case LoggerLevelDebug:
- return zapcore.DebugLevel
- case LoggerLevelWarn:
- return zapcore.WarnLevel
- default:
- return zapcore.DebugLevel
- }
- }
- var logger *zap.Logger
- var initLoggerOnce sync.Once
- const logDir = "logs"
- func lazyInitialize() {
- initLoggerOnce.Do(func() {
- logFilePath := filepath.Join(logDir, "log")
- lumberJackLogger := &lumberjack.Logger{
- Filename: logFilePath,
- MaxSize: 1,
- MaxAge: 10,
- }
- developmentEncoderConfig := zap.NewDevelopmentEncoderConfig()
- encoder := zapcore.NewConsoleEncoder(developmentEncoderConfig)
- core := zapcore.NewTee(
- zapcore.NewCore(encoder, zapcore.AddSync(lumberJackLogger), chooseLoggerLever()),
- zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), chooseLoggerLever()),
- )
- logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
- })
- }
- func Info(message string) {
- lazyInitialize()
- logger.Info(message)
- }
- func Error(err error) {
- lazyInitialize()
- message := fmt.Sprintf("\n%+v\n", err)
- logger.Error(message)
- }
- func Debug(message string) {
- lazyInitialize()
- logger.Debug(message)
- }
- func Warn(message string) {
- lazyInitialize()
- logger.Warn(message)
- }
|