log.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. #include <stdarg.h>
  3. #include <stdio.h>
  4. #include "log.h"
  5. /*
  6. * Note that the logging library is not thread safe, thus calls on separate
  7. * threads will yield an interleaved output on stderr.
  8. */
  9. static log_level current_log_level = log_level_warning;
  10. void log_set_level(log_level value) {
  11. current_log_level = value;
  12. }
  13. static const char *
  14. get_level_msg(log_level level) {
  15. const char *value = "UNK";
  16. switch (level) {
  17. case log_level_error:
  18. value = "ERROR";
  19. break;
  20. case log_level_warning:
  21. value = "WARN";
  22. break;
  23. case log_level_verbose:
  24. value = "INFO";
  25. }
  26. return value;
  27. }
  28. void _log(log_level level, const char *file, unsigned lineno, const char *fmt,
  29. ...) {
  30. /* Skip printing messages outside of the log level */
  31. if (level > current_log_level)
  32. return;
  33. va_list argptr;
  34. va_start(argptr, fmt);
  35. /* Verbose output prints file and line on error */
  36. if (current_log_level >= log_level_verbose) {
  37. fprintf(stderr, "%s on line: \"%u\" in file: \"%s\": ",
  38. get_level_msg(level), lineno, file);
  39. } else {
  40. fprintf(stderr, "%s: ", get_level_msg(level));
  41. }
  42. /* Print the user supplied message */
  43. vfprintf(stderr, fmt, argptr);
  44. /* always add a new line so the user doesn't have to */
  45. fprintf(stderr, "\n");
  46. va_end(argptr);
  47. }