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