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.

89 lines
2.1 KiB

  1. package flags
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "github.com/tendermint/tendermint/libs/log"
  7. )
  8. const (
  9. defaultLogLevelKey = "*"
  10. )
  11. // ParseLogLevel parses complex log level - comma-separated
  12. // list of module:level pairs with an optional *:level pair (* means
  13. // all other modules).
  14. //
  15. // Example:
  16. // ParseLogLevel("consensus:debug,mempool:debug,*:error", log.NewTMLogger(os.Stdout), "info")
  17. func ParseLogLevel(lvl string, logger log.Logger, defaultLogLevelValue string) (log.Logger, error) {
  18. if lvl == "" {
  19. return nil, errors.New("empty log level")
  20. }
  21. l := lvl
  22. // prefix simple one word levels (e.g. "info") with "*"
  23. if !strings.Contains(l, ":") {
  24. l = defaultLogLevelKey + ":" + l
  25. }
  26. options := make([]log.Option, 0)
  27. isDefaultLogLevelSet := false
  28. var option log.Option
  29. var err error
  30. list := strings.Split(l, ",")
  31. for _, item := range list {
  32. moduleAndLevel := strings.Split(item, ":")
  33. if len(moduleAndLevel) != 2 {
  34. return nil, fmt.Errorf("expected list in a form of \"module:level\" pairs, given pair %s, list %s", item, list)
  35. }
  36. module := moduleAndLevel[0]
  37. level := moduleAndLevel[1]
  38. if module == defaultLogLevelKey {
  39. option, err = log.AllowLevel(level)
  40. if err != nil {
  41. return nil, fmt.Errorf("failed to parse default log level (pair %s, list %s): %w", item, l, err)
  42. }
  43. options = append(options, option)
  44. isDefaultLogLevelSet = true
  45. } else {
  46. switch level {
  47. case "debug":
  48. option = log.AllowDebugWith("module", module)
  49. case "info":
  50. option = log.AllowInfoWith("module", module)
  51. case "error":
  52. option = log.AllowErrorWith("module", module)
  53. case "none":
  54. option = log.AllowNoneWith("module", module)
  55. default:
  56. return nil,
  57. fmt.Errorf("expected either \"info\", \"debug\", \"error\" or \"none\" log level, given %s (pair %s, list %s)",
  58. level,
  59. item,
  60. list)
  61. }
  62. options = append(options, option)
  63. }
  64. }
  65. // if "*" is not provided, set default global level
  66. if !isDefaultLogLevelSet {
  67. option, err = log.AllowLevel(defaultLogLevelValue)
  68. if err != nil {
  69. return nil, err
  70. }
  71. options = append(options, option)
  72. }
  73. return log.NewFilter(logger, options...), nil
  74. }