pr_log.c 811 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* Licensed under LGPLv2.1+ - see LICENSE file for details */
  2. #include "pr_log.h"
  3. #include <ctype.h>
  4. #include <stdarg.h>
  5. #include <stdbool.h>
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <limits.h>
  9. #include <ccan/str/str.h>
  10. #define DEBUG_NEED_INIT INT_MIN
  11. static int debug = DEBUG_NEED_INIT;
  12. bool debug_is(int lvl)
  13. {
  14. return lvl <= debug_level();
  15. }
  16. int debug_level(void)
  17. {
  18. if (debug != DEBUG_NEED_INIT)
  19. return debug;
  20. char *c = getenv("DEBUG");
  21. if (!c) {
  22. debug = CCAN_PR_LOG_DEFAULT_LEVEL;
  23. return debug;
  24. }
  25. debug = atoi(c);
  26. return debug;
  27. }
  28. void pr_log_(char const *fmt, ...)
  29. {
  30. int level = INT_MIN;
  31. if (fmt[0] == '<' && cisdigit(fmt[1]) && fmt[2] == '>')
  32. level = fmt[1] - '0';
  33. if (!debug_is(level))
  34. return;
  35. va_list va;
  36. va_start(va, fmt);
  37. vfprintf(stderr, fmt, va);
  38. va_end(va);
  39. }