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.

86 lines
2.1 KiB

  1. package flags
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/pkg/errors"
  6. "github.com/tendermint/tmlibs/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, errors.Wrap(err, fmt.Sprintf("Failed to parse default log level (pair %s, list %s)", item, l))
  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, fmt.Errorf("Expected either \"info\", \"debug\", \"error\" or \"none\" log level, given %s (pair %s, list %s)", level, item, list)
  57. }
  58. options = append(options, option)
  59. }
  60. }
  61. // if "*" is not provided, set default global level
  62. if !isDefaultLogLevelSet {
  63. option, err = log.AllowLevel(defaultLogLevelValue)
  64. if err != nil {
  65. return nil, err
  66. }
  67. options = append(options, option)
  68. }
  69. return log.NewFilter(logger, options...), nil
  70. }