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.

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