gins_log.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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/os/glog"
  12. "github.com/gogf/gf/v2/util/gutil"
  13. )
  14. const (
  15. frameCoreComponentNameLogger = "gf.core.component.logger"
  16. )
  17. // Log returns an instance of glog.Logger.
  18. // The parameter `name` is the name for the instance.
  19. // Note that it panics if any error occurs duration instance creating.
  20. func Log(name ...string) *glog.Logger {
  21. var (
  22. ctx = context.Background()
  23. instanceName = glog.DefaultName
  24. )
  25. if len(name) > 0 && name[0] != "" {
  26. instanceName = name[0]
  27. }
  28. instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameLogger, instanceName)
  29. return localInstances.GetOrSetFuncLock(instanceKey, func() interface{} {
  30. logger := glog.Instance(instanceName)
  31. // To avoid file no found error while it's not necessary.
  32. var (
  33. configMap map[string]interface{}
  34. loggerNodeName = consts.ConfigNodeNameLogger
  35. )
  36. // Try to find possible `loggerNodeName` in case-insensitive way.
  37. if configData, _ := Config().Data(ctx); len(configData) > 0 {
  38. if v, _ := gutil.MapPossibleItemByKey(configData, consts.ConfigNodeNameLogger); v != "" {
  39. loggerNodeName = v
  40. }
  41. }
  42. // Retrieve certain logger configuration by logger name.
  43. certainLoggerNodeName := fmt.Sprintf(`%s.%s`, loggerNodeName, instanceName)
  44. if v, _ := Config().Get(ctx, certainLoggerNodeName); !v.IsEmpty() {
  45. configMap = v.Map()
  46. }
  47. // Retrieve global logger configuration if configuration for certain logger name does not exist.
  48. if len(configMap) == 0 {
  49. if v, _ := Config().Get(ctx, loggerNodeName); !v.IsEmpty() {
  50. configMap = v.Map()
  51. }
  52. }
  53. // Set logger config if config map is not empty.
  54. if len(configMap) > 0 {
  55. if err := logger.SetConfigWithMap(configMap); err != nil {
  56. panic(err)
  57. }
  58. }
  59. return logger
  60. }).(*glog.Logger)
  61. }