log.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // SPDX-License-Identifier: LGPL-2.1+
  2. // Copyright (C) 2022, Linaro Ltd - Daniel Lezcano <daniel.lezcano@linaro.org>
  3. #include <stdarg.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <syslog.h>
  7. #include "log.h"
  8. static const char *__ident = "unknown";
  9. static int __options;
  10. static const char * const loglvl[] = {
  11. [LOG_DEBUG] = "DEBUG",
  12. [LOG_INFO] = "INFO",
  13. [LOG_NOTICE] = "NOTICE",
  14. [LOG_WARNING] = "WARN",
  15. [LOG_ERR] = "ERROR",
  16. [LOG_CRIT] = "CRITICAL",
  17. [LOG_ALERT] = "ALERT",
  18. [LOG_EMERG] = "EMERG",
  19. };
  20. int log_str2level(const char *lvl)
  21. {
  22. int i;
  23. for (i = 0; i < sizeof(loglvl) / sizeof(loglvl[LOG_DEBUG]); i++)
  24. if (!strcmp(lvl, loglvl[i]))
  25. return i;
  26. return LOG_DEBUG;
  27. }
  28. extern void logit(int level, const char *format, ...)
  29. {
  30. va_list args;
  31. va_start(args, format);
  32. if (__options & TO_SYSLOG)
  33. vsyslog(level, format, args);
  34. if (__options & TO_STDERR)
  35. vfprintf(stderr, format, args);
  36. if (__options & TO_STDOUT)
  37. vfprintf(stdout, format, args);
  38. va_end(args);
  39. }
  40. int log_init(int level, const char *ident, int options)
  41. {
  42. if (!options)
  43. return -1;
  44. if (level > LOG_DEBUG)
  45. return -1;
  46. if (!ident)
  47. return -1;
  48. __ident = ident;
  49. __options = options;
  50. if (options & TO_SYSLOG) {
  51. openlog(__ident, options | LOG_NDELAY, LOG_USER);
  52. setlogmask(LOG_UPTO(level));
  53. }
  54. return 0;
  55. }
  56. void log_exit(void)
  57. {
  58. closelog();
  59. }