You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

236 lines
5.5 KiB

3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
  1. package log
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/fs"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "path"
  10. "time"
  11. "github.com/BurntSushi/toml"
  12. "go.uber.org/zap"
  13. "go.uber.org/zap/zapcore"
  14. "gopkg.in/yaml.v2"
  15. )
  16. var (
  17. logger Logger
  18. )
  19. type YLogger struct {
  20. Logger
  21. dynamicLevel zap.AtomicLevel
  22. }
  23. type Logger interface {
  24. Info(args ...interface{})
  25. Warn(args ...interface{})
  26. Error(args ...interface{})
  27. Debug(args ...interface{})
  28. Infof(fmt string, args ...interface{})
  29. Warnf(fmt string, args ...interface{})
  30. Errorf(fmt string, args ...interface{})
  31. Debugf(fmt string, args ...interface{})
  32. }
  33. func init() {
  34. var (
  35. cfg LogCfg
  36. logCfg GlobalCfg
  37. )
  38. log.Println("config file name -->", ConfigFile)
  39. log.Println("starting ...")
  40. if _, err := toml.DecodeFile(ConfigFile, &logCfg); err != nil {
  41. //log.Fatalf("Read config file err:%s", err.Error())
  42. log.Println("failed to open config file")
  43. if err = InitLog("", cfg); nil != err {
  44. log.Println(err.Error())
  45. }
  46. return
  47. }
  48. cfg = logCfg.Logs
  49. cfg.OutputPaths = cfg.LogPath + cfg.APPName + time.Now().Format("2006-01-02") + ".log"
  50. cfg.ErrorOutputPaths = cfg.LogPath + cfg.APPName + ".error"
  51. err := InitLog(cfg.LogConf, cfg)
  52. if err != nil {
  53. log.Printf("[InitLog] warn: %v", err)
  54. }
  55. }
  56. func ReloadLogger(configFile string) {
  57. var (
  58. cfg LogCfg
  59. logCfg GlobalCfg
  60. )
  61. log.Println("config file name -->", configFile)
  62. if _, err := toml.DecodeFile(configFile, &logCfg); err != nil {
  63. log.Fatalf("Read config file err:%s", err.Error())
  64. }
  65. cfg = logCfg.Logs
  66. cfg.OutputPaths = cfg.LogPath + cfg.APPName + time.Now().Format("2006-01-02") + ".log"
  67. cfg.ErrorOutputPaths = cfg.LogPath + cfg.APPName + ".error"
  68. err := InitLog(cfg.LogConf, cfg)
  69. if err != nil {
  70. log.Printf("[ReloadLogger] warn: %v", err)
  71. }
  72. }
  73. func RotateLogger(cfg LogCfg) {
  74. cfg.OutputPaths = cfg.LogInfoPath + cfg.APPName + ".log"
  75. cfg.ErrorOutputPaths = cfg.LogErrPath + cfg.APPName + ".error"
  76. if _, err := os.Stat(cfg.OutputPaths); errors.Is(err, fs.ErrNotExist) {
  77. if _, err = os.Create(cfg.OutputPaths); nil != err {
  78. log.Printf("[RotateLogger] error: %s", err.Error())
  79. return
  80. }
  81. }
  82. //if _, err := os.Stat(cfg.ErrorOutputPaths); errors.Is(err, fs.ErrNotExist) {
  83. // if _, err = os.Create(cfg.ErrorOutputPaths); nil != err {
  84. // log.Printf("[RotateLogger] error: %s", err.Error())
  85. // return
  86. // }
  87. //}
  88. err := InitLog(cfg.LogConf, cfg)
  89. if err != nil {
  90. log.Printf("[RotateLogger] warn: %v", err)
  91. }
  92. }
  93. var defaultZapConfig = []byte(`
  94. level: "info"
  95. development: false
  96. disableCaller: false
  97. disableStacktrace: false
  98. sampling:
  99. encoding: "console"
  100. # encoder
  101. encoderConfig:
  102. messageKey: "message"
  103. levelKey: "level"
  104. timeKey: "time"
  105. nameKey: "logger"
  106. callerKey: "caller"
  107. stacktraceKey: "stacktrace"
  108. lineEnding: ""
  109. # levelEncoder: "capitalColor"
  110. timeEncoder: "iso8601"
  111. durationEncoder: "seconds"
  112. callerEncoder: "short"
  113. nameEncoder: ""
  114. `)
  115. func InitLog(logConfFile string, cfg LogCfg) error {
  116. conf := &zap.Config{}
  117. if logConfFile != "" {
  118. if path.Ext(logConfFile) != ".yml" {
  119. InitLogger(nil)
  120. return fmt.Errorf("log configure file name{%s} suffix must be .yml", logConfFile)
  121. }
  122. confFileStream, err := ioutil.ReadFile(logConfFile)
  123. if err != nil {
  124. InitLogger(nil)
  125. return fmt.Errorf("ioutil.ReadFile(file:%s) = error:%v", logConfFile, err)
  126. }
  127. err = yaml.Unmarshal(confFileStream, conf)
  128. if err != nil {
  129. InitLogger(nil)
  130. return fmt.Errorf("[Unmarshal]init logger error: %v", err)
  131. }
  132. } else {
  133. conf = &zap.Config{
  134. Level: zap.NewAtomicLevel(),
  135. Development: false,
  136. DisableCaller: false,
  137. DisableStacktrace: false,
  138. Sampling: nil,
  139. Encoding: "console",
  140. EncoderConfig: zapcore.EncoderConfig{
  141. MessageKey: "message",
  142. LevelKey: "level",
  143. TimeKey: "time",
  144. NameKey: "logger",
  145. CallerKey: "caller",
  146. StacktraceKey: "stacktrace",
  147. EncodeTime: zapcore.EpochMillisTimeEncoder,
  148. EncodeDuration: zapcore.SecondsDurationEncoder,
  149. EncodeCaller: zapcore.ShortCallerEncoder,
  150. EncodeName: nil,
  151. EncodeLevel: nil,
  152. },
  153. }
  154. err := yaml.Unmarshal(defaultZapConfig, conf)
  155. if err != nil {
  156. InitLogger(nil)
  157. return fmt.Errorf("[Unmarshal]init logger error: %v", err)
  158. }
  159. }
  160. conf.OutputPaths = append(conf.OutputPaths, cfg.OutputPaths)
  161. conf.ErrorOutputPaths = append(conf.ErrorOutputPaths, cfg.ErrorOutputPaths)
  162. InitLogger(conf)
  163. return nil
  164. }
  165. func InitLogger(conf *zap.Config) {
  166. var zapLoggerConfig zap.Config
  167. if conf == nil {
  168. zapLoggerConfig = zap.NewDevelopmentConfig()
  169. zapLoggerEncoderConfig := zapcore.EncoderConfig{
  170. TimeKey: "time",
  171. LevelKey: "level",
  172. NameKey: "logger",
  173. CallerKey: "caller",
  174. MessageKey: "message",
  175. StacktraceKey: "stacktrace",
  176. EncodeTime: zapcore.ISO8601TimeEncoder,
  177. EncodeDuration: zapcore.SecondsDurationEncoder,
  178. EncodeCaller: zapcore.ShortCallerEncoder,
  179. }
  180. zapLoggerConfig.EncoderConfig = zapLoggerEncoderConfig
  181. } else {
  182. zapLoggerConfig = *conf
  183. }
  184. zapLogger, _ := zapLoggerConfig.Build(zap.AddCallerSkip(1))
  185. //logger = zapLogger.Sugar()
  186. logger = &YLogger{Logger: zapLogger.Sugar(), dynamicLevel: zapLoggerConfig.Level}
  187. }
  188. func SetLogger(log Logger) {
  189. logger = log
  190. }
  191. func GetLogger() Logger {
  192. return logger
  193. }
  194. func SetLoggerLevel(level string) bool {
  195. if l, ok := logger.(OpsLogger); ok {
  196. l.SetLoggerLevel(level)
  197. return true
  198. }
  199. return false
  200. }
  201. type OpsLogger interface {
  202. Logger
  203. SetLoggerLevel(level string)
  204. }
  205. func (dl *YLogger) SetLoggerLevel(level string) {
  206. l := new(zapcore.Level)
  207. l.Set(level)
  208. dl.dynamicLevel.SetLevel(*l)
  209. }