log.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #include <stdarg.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <syslog.h>
  6. #include <time.h>
  7. #include "log.h"
  8. /*
  9. * The minimum log level; set to one of L_* constants from log.h
  10. */
  11. int min_log_level = 666;
  12. /*
  13. * 0: send output to stderr
  14. * 1: send output to syslog LOG_LOCAL1 facility
  15. */
  16. int use_syslog = 0;
  17. /* Turn log level number to a printable string */
  18. char *log_printable_level(int level)
  19. {
  20. switch(level)
  21. {
  22. case L_ERROR:
  23. return "ERROR";
  24. case L_WARNING:
  25. return "WARNING";
  26. case L_NOTICE:
  27. return "NOTICE";
  28. case L_INFO:
  29. return "INFO";
  30. case L_DEBUG:
  31. return "DEBUG";
  32. }
  33. return "UNKNOWN";
  34. }
  35. void log_init(void)
  36. {
  37. if(use_syslog)
  38. {
  39. openlog("tuntox", LOG_PID, LOG_LOCAL1);
  40. }
  41. }
  42. void log_close(void)
  43. {
  44. if(use_syslog)
  45. {
  46. closelog();
  47. }
  48. }
  49. /* Output the log to the console */
  50. void log_printf(int level, const char *fmt, ...)
  51. {
  52. va_list args;
  53. char logfmt[2048];
  54. char logtime[100];
  55. char *level_str;
  56. time_t rawtime;
  57. struct tm *timeinfo;
  58. if(level > min_log_level)
  59. {
  60. return;
  61. }
  62. if(!use_syslog)
  63. {
  64. time(&rawtime);
  65. timeinfo = localtime(&rawtime);
  66. strftime(logtime, 100, "%F %X", timeinfo);
  67. level_str = log_printable_level(level);
  68. if(fmt[strlen(fmt)-1] == '\n')
  69. {
  70. snprintf(logfmt, 2048, "%s: [%s]\t%s", logtime, level_str, fmt);
  71. }
  72. else
  73. {
  74. snprintf(logfmt, 2048, "%s: [%s]\t%s\n", logtime, level_str, fmt);
  75. }
  76. va_start(args, fmt);
  77. vfprintf(stderr, logfmt, args);
  78. va_end(args);
  79. }
  80. else
  81. {
  82. va_start(args, fmt);
  83. vsyslog(LOG_MAKEPRI(LOG_LOCAL1, level), fmt, args);
  84. va_end(args);
  85. }
  86. }
  87. void log_test(void)
  88. {
  89. int i = 112;
  90. char *x = "test";
  91. log_printf(L_WARNING, "Testing");
  92. log_printf(L_ERROR, "Number stodwadziesciatrzy: %d", 123);
  93. d(beenthere);
  94. dd(i);
  95. dp(&i);
  96. ds(x);
  97. }