There are seven log levels supported by logrus but let's not expose all that to the user. Instead let's say we have the following effective modes of logging: "debug", "verbose", "quiet" and "normal" i.e. the default. "Quiet" shows ErrorLevel messages and higher. "Normal" shows WarnLevel messages an
(verbose, quiet, debug, trace bool, logfile string)
| 44 | // there are multiple set we'll accept it and the more verbose |
| 45 | // option will take precedence. |
| 46 | func InitLogging(verbose, quiet, debug, trace bool, logfile string) { |
| 47 | var level log.Level |
| 48 | var v string |
| 49 | switch { |
| 50 | case trace: |
| 51 | level = log.TraceLevel |
| 52 | setupDebugMode() |
| 53 | v = "9" |
| 54 | case debug: |
| 55 | level = log.DebugLevel |
| 56 | setupDebugMode() |
| 57 | v = "6" |
| 58 | case verbose: |
| 59 | level = log.DebugLevel |
| 60 | v = "6" |
| 61 | case quiet: |
| 62 | level = log.ErrorLevel |
| 63 | v = "1" |
| 64 | default: |
| 65 | level = log.WarnLevel |
| 66 | v = "1" |
| 67 | } |
| 68 | |
| 69 | log.SetLevel(level) |
| 70 | |
| 71 | // The problem with klog is that it'll log to stdout/stderr, we want to |
| 72 | // control the logging and log via logrus instead. This accomplishes that |
| 73 | // but at the cost of loosing log levels, i.e. all klog messages will be |
| 74 | // logged with the INFO level. |
| 75 | // see |
| 76 | // https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md |
| 77 | // https://github.com/kubernetes/klog/issues/87 |
| 78 | klog.SetLogger(logr.New(&logrusSink{}).V(int(level))) |
| 79 | flags := &flag.FlagSet{} |
| 80 | klog.InitFlags(flags) |
| 81 | if err := flags.Set("v", v); err != nil { |
| 82 | panic(err) |
| 83 | } |
| 84 | |
| 85 | if logfile != "" { |
| 86 | if l, err := os.OpenFile(logfile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600); err == nil { |
| 87 | log.SetOutput(l) |
| 88 | } else { |
| 89 | fmt.Fprintf(os.Stderr, "Unable to create log file %q, log lines will appear on standard error. Error was: %s\n", logfile, err.Error()) |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | func setupDebugMode() { |
| 95 | // Show the file, line number and function name when logging |
no test coverage detected