package main // log.go: logging import ( "fmt" "os" "strings" "github.com/fatih/color" ) func init() { registerParam("log-level", 0, "max log level, useful for debugging. -1 logs everything") registerParamWithCallback("log-modules", []string{}, "always log output from these modules", updateModuleMap) registerParamWithCallback("no-log-modules", []string{}, "never log output from these modules", updateModuleMap) registerParamHidden("log-module-map", map[string]bool{}) registerCommand("no-colors", "disable terminal colors", func() { color.NoColor = true }) } func shouldLog(facility string, level, maxLevel int) bool { moduleMap := getParam[map[string]bool]("log-module-map") logModule, ok := moduleMap[strings.ToLower(facility)] if ok { return logModule } if maxLevel < 0 { return true // log everything if log-level is -1 } return maxLevel >= level } func log(facility string, level int, s string, params ...interface{}) { maxLevel := getParamInt("log-level") if !shouldLog(facility, level, maxLevel) { return } var prefix = "" if level > 0 { prefix = color.WhiteString(strings.Repeat("-", level) + "> ") } if (level >= 1 || maxLevel < 0) && facility != "" { prefix = prefix + color.CyanString("["+strings.ToUpper(facility)+"]: ") } if len(params) == 0 { fmt.Printf(prefix + s + "\n") } else { fmt.Printf(prefix+s+"\n", params...) } } func fail(s string, params ...any) { if len(params) == 0 { fmt.Fprintf(os.Stderr, color.HiRedString("ERROR: ")+s+"\n") } else { fmt.Fprintf(os.Stderr, color.HiRedString("ERROR: ")+s+"\n", params...) } os.Exit(1) } func logIf(condition bool, facility string, level int, s string, params ...interface{}) { if condition { log(facility, level, s, params...) } } func failIf(condition bool, s string, params ...interface{}) { if condition { fail(s, params...) } } func updateModuleMap() { logModules := getParamStringSlice("log-modules") noLogModules := getParamStringSlice("no-log-modules") newMap := map[string]bool{} for _, module := range logModules { module = strings.ToLower(module) newMap[module] = true } for _, module := range noLogModules { module = strings.ToLower(module) failIf(newMap[module], "log module \"%v\" is defined both in log-modules and no-log-modules", module) newMap[module] = false } setParam("log-module-map", newMap) }