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.
91 lines
2.1 KiB
91 lines
2.1 KiB
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
func shouldLog(facility string, level, maxLevel int) bool {
|
|
moduleMap := CfgGet("log-module-map").(map[string]bool)
|
|
|
|
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 := CfgGetInt("log-level")
|
|
if !shouldLog(facility, level, maxLevel) {
|
|
return
|
|
}
|
|
|
|
var prefix = ""
|
|
if level > 0 {
|
|
prefix = strings.Repeat("-", level) + "> "
|
|
}
|
|
if (maxLevel >= 2 || maxLevel < 0) && facility != "" {
|
|
prefix = prefix + "[" + strings.ToUpper(facility) + "]: "
|
|
}
|
|
|
|
if len(params) == 0 {
|
|
fmt.Printf(prefix + s + "\n")
|
|
} else {
|
|
fmt.Printf(prefix+s+"\n", params...)
|
|
}
|
|
}
|
|
|
|
func fail(s string, params ...interface{}) {
|
|
if len(params) == 0 {
|
|
fmt.Fprintf(os.Stderr, "ERROR: "+s+"\n")
|
|
} else {
|
|
fmt.Fprintf(os.Stderr, "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 := CfgGet("log-modules").([]string)
|
|
noLogModules := CfgGet("no-log-modules").([]string)
|
|
|
|
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] == true, "log module \"%v\" is defined both in log-modules and no-log-modules", module)
|
|
newMap[module] = false
|
|
}
|
|
|
|
CfgSet("log-module-map", newMap)
|
|
}
|
|
|
|
func init() {
|
|
CfgRegister("log-level", 0, "max log level, useful for debugging. -1 logs everything")
|
|
CfgRegisterCallback("log-modules", []string{}, "always log output from these modules", updateModuleMap)
|
|
CfgRegisterCallback("no-log-modules", []string{}, "never log output from these modules", updateModuleMap)
|
|
CfgRegisterHidden("log-module-map", map[string]bool{})
|
|
}
|
|
|