高热共公日志库
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.

106 lines
2.0 KiB

  1. package grlogs
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "golib.gaore.com/GaoreGo/grlogs/logs"
  7. "os"
  8. "path"
  9. "sync"
  10. )
  11. const (
  12. _ = iota
  13. LEVEL_NONE = iota
  14. LEVEL_CRITICAL = iota
  15. LEVEL_ERROR = iota
  16. LEVEL_WARNING = iota
  17. LEVEL_WARN = iota
  18. LEVEL_INFO = iota
  19. LEVEL_DEBUG = iota
  20. LEVEL_ALL = iota
  21. )
  22. type ConsoleLogConfig struct {
  23. Level int `json:"level"`
  24. }
  25. type FileLogConfig struct {
  26. Filename string `json:"filename"`
  27. Level int `json:"level"`
  28. Maxlines int `json:"maxlines"`
  29. Daily bool `json:"daily"`
  30. Maxdays int `json:"maxdays"`
  31. Color bool `json:"color"`
  32. Rotate bool `json:"rotate"`
  33. }
  34. type ConnLogConfig struct {
  35. ReconnectOnMsg bool `json:"reconnect_on_msg"`
  36. Reconnect bool `json:"reconnect"`
  37. Net string `json:"net"`
  38. Addr string `json:"addr"`
  39. Level int `json:"level"`
  40. }
  41. var loggers = sync.Map{}
  42. type Logger struct {
  43. *logs.BeeLogger
  44. }
  45. func (l *Logger) Write(p []byte) (n int, err error) {
  46. l.Debug(bytes.NewBuffer(p).String())
  47. return
  48. }
  49. func (l *Logger) SetFormat() {
  50. }
  51. func (l *Logger) Stop() {
  52. l.BeeLogger.Close()
  53. }
  54. func GetLogger(name string) *Logger {
  55. if l, ok := loggers.Load(name); ok {
  56. return l.(*Logger)
  57. } else {
  58. var level int = LEVEL_WARN
  59. if s := os.Getenv("CENTER_RUNMODE"); s == "dev" {
  60. level = LEVEL_ALL
  61. }
  62. wd, _ := os.Getwd()
  63. conf1 := FileLogConfig{
  64. Filename: path.Join(wd, fmt.Sprintf("runtime/logs/%s.log", name)),
  65. Level: LEVEL_ALL,
  66. Maxlines: 0,
  67. Daily: true,
  68. Maxdays: 7,
  69. Color: true,
  70. Rotate: true,
  71. }
  72. conf2 := ConsoleLogConfig{
  73. Level: level,
  74. }
  75. confString, _ := json.Marshal(&conf1)
  76. confString2, _ := json.Marshal(&conf2)
  77. l := new(Logger)
  78. l.BeeLogger = logs.NewLogger()
  79. l.SetLogger(logs.AdapterFile, bytes.NewBuffer(confString).String())
  80. l.SetLogger(logs.AdapterConsole, bytes.NewBuffer(confString2).String())
  81. l.BeeLogger.SetPrefix("_" + name)
  82. l.BeeLogger.EnableFuncCallDepth(true)
  83. l.BeeLogger.SetLogFuncCallDepth(2)
  84. loggers.Store(name, l)
  85. return l
  86. }
  87. }