build/log: support parsing global+subsystem levels

This makes it possible to specify both a global+subsystem loglevels,
like:
--debuglevel=debug,PEER=info,SRVR=trace
This commit is contained in:
Johan T. Halseth 2020-11-16 11:22:57 +01:00
parent fcf2e7f687
commit c1d423dc07
No known key found for this signature in database
GPG Key ID: 15BAADA29DA20D26
2 changed files with 32 additions and 10 deletions

@ -122,24 +122,32 @@ type LeveledSubLogger interface {
// the levels accordingly on the given logger. An appropriate error is returned // the levels accordingly on the given logger. An appropriate error is returned
// if anything is invalid. // if anything is invalid.
func ParseAndSetDebugLevels(level string, logger LeveledSubLogger) error { func ParseAndSetDebugLevels(level string, logger LeveledSubLogger) error {
// When the specified string doesn't have any delimiters, treat it as // Split at the delimiter.
// the log level for all subsystems. levels := strings.Split(level, ",")
if !strings.Contains(level, ",") && !strings.Contains(level, "=") { if len(levels) == 0 {
return fmt.Errorf("invalid log level: %v", level)
}
// If the first entry has no =, treat is as the log level for all
// subsystems.
globalLevel := levels[0]
if !strings.Contains(globalLevel, "=") {
// Validate debug log level. // Validate debug log level.
if !validLogLevel(level) { if !validLogLevel(globalLevel) {
str := "the specified debug level [%v] is invalid" str := "the specified debug level [%v] is invalid"
return fmt.Errorf(str, level) return fmt.Errorf(str, globalLevel)
} }
// Change the logging level for all subsystems. // Change the logging level for all subsystems.
logger.SetLogLevels(level) logger.SetLogLevels(globalLevel)
return nil // The rest will target specific subsystems.
levels = levels[1:]
} }
// Split the specified string into subsystem/level pairs while detecting // Go through the subsystem/level pairs while detecting issues and
// issues and update the log levels accordingly. // update the log levels accordingly.
for _, logLevelPair := range strings.Split(level, ",") { for _, logLevelPair := range levels {
if !strings.Contains(logLevelPair, "=") { if !strings.Contains(logLevelPair, "=") {
str := "the specified debug level contains an " + str := "the specified debug level contains an " +
"invalid subsystem/level pair [%v]" "invalid subsystem/level pair [%v]"

@ -75,6 +75,20 @@ func TestParseAndSetDebugLevels(t *testing.T) {
"SRVR": "debug", "SRVR": "debug",
}, },
}, },
{
name: "valid global+subsystem debug level",
debugLevel: "trace,PEER=info,SRVR=debug",
expGlobal: "trace",
expSubLevels: map[string]string{
"PEER": "info",
"SRVR": "debug",
},
},
{
name: "invalid global+subsystem debug level",
debugLevel: "PEER=info,debug,SRVR=debug",
expErr: "invalid",
},
} }
for _, test := range testCases { for _, test := range testCases {