github.com/openshift/dpu-operator@v0.0.0-20240502153209-3af840d137c2/dpu-cni/pkgs/cnilogging/cnilogging.go (about) 1 // package cnilogging is a small wrapper around github.com/k8snetworkplumbingwg/cni-log 2 3 package cnilogging 4 5 import ( 6 cnilog "github.com/k8snetworkplumbingwg/cni-log" 7 ) 8 9 const ( 10 labelCNIName = "cniName" 11 labelContainerID = "containerID" 12 labelNetNS = "netns" 13 labelIFName = "ifname" 14 cniName = "dpu-sriov-cni" 15 ) 16 17 var ( 18 logLevelDefault = cnilog.InfoLevel 19 containerID = "" 20 netNS = "" 21 ifName = "" 22 ) 23 24 // Init initializes logging with the requested parameters in this order: log level, log file, container ID, 25 // network namespace and interface name. 26 func Init(logLevel, logFile, containerIdentification, networkNamespace, interfaceName string) { 27 setLogLevel(logLevel) 28 setLogFile(logFile) 29 containerID = containerIdentification 30 netNS = networkNamespace 31 ifName = interfaceName 32 } 33 34 // setLogLevel sets the log level to either verbose, debug, info, warn, error or panic. If an invalid string is 35 // provided, it uses error. 36 func setLogLevel(l string) { 37 ll := cnilog.StringToLevel(l) 38 if ll == cnilog.InvalidLevel { 39 ll = logLevelDefault 40 } 41 cnilog.SetLogLevel(ll) 42 } 43 44 // setLogFile sets the log file for logging. If the empty string is provided, it uses stderr. 45 func setLogFile(fileName string) { 46 if fileName == "" { 47 cnilog.SetLogStderr(true) 48 cnilog.SetLogFile("") 49 return 50 } 51 cnilog.SetLogFile(fileName) 52 cnilog.SetLogStderr(false) 53 } 54 55 // Debug provides structured logging for log level >= debug. 56 func Debug(msg string, args ...interface{}) { 57 cnilog.DebugStructured(msg, prependArgs(args)...) 58 } 59 60 // Info provides structured logging for log level >= info. 61 func Info(msg string, args ...interface{}) { 62 cnilog.InfoStructured(msg, prependArgs(args)...) 63 } 64 65 // Warning provides structured logging for log level >= warning. 66 func Warning(msg string, args ...interface{}) { 67 cnilog.WarningStructured(msg, prependArgs(args)...) 68 } 69 70 // Error provides structured logging for log level >= error. 71 func Error(msg string, args ...interface{}) { 72 _ = cnilog.ErrorStructured(msg, prependArgs(args)...) 73 } 74 75 // Panic provides structured logging for log level >= panic. 76 func Panic(msg string, args ...interface{}) { 77 cnilog.PanicStructured(msg, prependArgs(args)...) 78 } 79 80 // prependArgs prepends cniName, containerID, netNS and ifName to the args of every log message. 81 func prependArgs(args []interface{}) []interface{} { 82 if ifName != "" { 83 args = append([]interface{}{labelIFName, ifName}, args...) 84 } 85 if netNS != "" { 86 args = append([]interface{}{labelNetNS, netNS}, args...) 87 } 88 if containerID != "" { 89 args = append([]interface{}{labelContainerID, containerID}, args...) 90 } 91 args = append([]interface{}{labelCNIName, cniName}, args...) 92 return args 93 }