gins_log.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gins
  7. import (
  8. "context"
  9. "fmt"
  10. "github.com/gogf/gf/v2/internal/consts"
  11. "github.com/gogf/gf/v2/internal/instance"
  12. "github.com/gogf/gf/v2/os/glog"
  13. "github.com/gogf/gf/v2/util/gutil"
  14. )
  15. // Log returns an instance of glog.Logger.
  16. // The parameter `name` is the name for the instance.
  17. // Note that it panics if any error occurs duration instance creating.
  18. func Log(name ...string) *glog.Logger {
  19. var (
  20. ctx = context.Background()
  21. instanceName = glog.DefaultName
  22. )
  23. if len(name) > 0 && name[0] != "" {
  24. instanceName = name[0]
  25. }
  26. instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameLogger, instanceName)
  27. return instance.GetOrSetFuncLock(instanceKey, func() interface{} {
  28. logger := glog.Instance(instanceName)
  29. // To avoid file no found error while it's not necessary.
  30. var (
  31. configMap map[string]interface{}
  32. loggerNodeName = consts.ConfigNodeNameLogger
  33. )
  34. // Try to find possible `loggerNodeName` in case-insensitive way.
  35. if configData, _ := Config().Data(ctx); len(configData) > 0 {
  36. if v, _ := gutil.MapPossibleItemByKey(configData, consts.ConfigNodeNameLogger); v != "" {
  37. loggerNodeName = v
  38. }
  39. }
  40. // Retrieve certain logger configuration by logger name.
  41. certainLoggerNodeName := fmt.Sprintf(`%s.%s`, loggerNodeName, instanceName)
  42. if v, _ := Config().Get(ctx, certainLoggerNodeName); !v.IsEmpty() {
  43. configMap = v.Map()
  44. }
  45. // Retrieve global logger configuration if configuration for certain logger name does not exist.
  46. if len(configMap) == 0 {
  47. if v, _ := Config().Get(ctx, loggerNodeName); !v.IsEmpty() {
  48. configMap = v.Map()
  49. }
  50. }
  51. // Set logger config if config map is not empty.
  52. if len(configMap) > 0 {
  53. if err := logger.SetConfigWithMap(configMap); err != nil {
  54. panic(err)
  55. }
  56. }
  57. return logger
  58. }).(*glog.Logger)
  59. }