github.com/GuanceCloud/cliutils@v1.1.21/logger/logger.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 package logger 7 8 import ( 9 "os" 10 "sync" 11 12 "go.uber.org/zap" 13 ) 14 15 const ( 16 // 禁用 JSON 形式输出. 17 OPT_ENC_CONSOLE = 1 //nolint:golint,stylecheck 18 // 显示代码路径时,不显示全路径. 19 OPT_SHORT_CALLER = 2 //nolint:stylecheck,golint 20 // 日志写到 stdout. 21 OPT_STDOUT = 4 //nolint:stylecheck,golint 22 // 日志内容中追加颜色. 23 OPT_COLOR = 8 //nolint:stylecheck,golint 24 // 日志自动切割. 25 OPT_ROTATE = 32 //nolint:stylecheck,golint 26 // 默认日志 flags. 27 OPT_DEFAULT = OPT_ENC_CONSOLE | OPT_SHORT_CALLER | OPT_ROTATE //nolint:stylecheck,golint 28 29 DEBUG = "debug" 30 INFO = "info" 31 WARN = "warn" 32 ERROR = "error" 33 PANIC = "panic" 34 DPANIC = "dpanic" 35 FATAL = "fatal" 36 ) 37 38 var ( 39 MaxSize = 32 // MB 40 MaxBackups = 5 41 MaxAge = 30 // day 42 43 mtx = &sync.Mutex{} 44 ) 45 46 type Logger struct { 47 *zap.SugaredLogger 48 } 49 50 type Option struct { 51 Path string 52 Level string 53 MaxSize int 54 Flags int 55 Compress bool 56 } 57 58 func Reset() { 59 mtx.Lock() 60 defer mtx.Unlock() 61 root = nil 62 63 slogs = &sync.Map{} 64 65 defaultStdoutRootLogger = nil 66 67 totalSloggers = 0 68 69 if err := doInitStdoutLogger(); err != nil { 70 panic(err.Error()) 71 } 72 } 73 74 func Close() { 75 if root != nil { 76 if err := root.Sync(); err != nil { 77 _ = err // pass 78 } 79 } 80 } 81 82 //nolint:gochecknoinits 83 func init() { 84 if err := doInitStdoutLogger(); err != nil { 85 panic(err.Error()) 86 } 87 88 if v, ok := os.LookupEnv("LOGGER_PATH"); ok { 89 opt := &Option{ 90 Level: DEBUG, 91 Flags: OPT_DEFAULT, 92 Path: v, 93 } 94 95 if err := setRootLoggerFromEnv(opt); err != nil { 96 panic(err.Error()) 97 } 98 } 99 }