debug.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package netlink
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. // Arguments used to create a debugger.
  10. var debugArgs []string
  11. func init() {
  12. // Is netlink debugging enabled?
  13. s := os.Getenv("NLDEBUG")
  14. if s == "" {
  15. return
  16. }
  17. debugArgs = strings.Split(s, ",")
  18. }
  19. // A debugger is used to provide debugging information about a netlink connection.
  20. type debugger struct {
  21. Log *log.Logger
  22. Level int
  23. }
  24. // newDebugger creates a debugger by parsing key=value arguments.
  25. func newDebugger(args []string) *debugger {
  26. d := &debugger{
  27. Log: log.New(os.Stderr, "nl: ", 0),
  28. Level: 1,
  29. }
  30. for _, a := range args {
  31. kv := strings.Split(a, "=")
  32. if len(kv) != 2 {
  33. // Ignore malformed pairs and assume callers wants defaults.
  34. continue
  35. }
  36. switch kv[0] {
  37. // Select the log level for the debugger.
  38. case "level":
  39. level, err := strconv.Atoi(kv[1])
  40. if err != nil {
  41. panicf("netlink: invalid NLDEBUG level: %q", a)
  42. }
  43. d.Level = level
  44. }
  45. }
  46. return d
  47. }
  48. // debugf prints debugging information at the specified level, if d.Level is
  49. // high enough to print the message.
  50. func (d *debugger) debugf(level int, format string, v ...interface{}) {
  51. if d.Level >= level {
  52. d.Log.Printf(format, v...)
  53. }
  54. }
  55. func panicf(format string, a ...interface{}) {
  56. panic(fmt.Sprintf(format, a...))
  57. }