log.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <stdarg.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <time.h>
  6. #include "log.h"
  7. int min_log_level = 666;
  8. /* Turn log level number to a printable string */
  9. char *log_printable_level(int level)
  10. {
  11. switch(level)
  12. {
  13. case L_ERROR:
  14. return "ERROR";
  15. case L_WARNING:
  16. return "WARNING";
  17. case L_NOTICE:
  18. return "NOTICE";
  19. case L_INFO:
  20. return "INFO";
  21. case L_DEBUG:
  22. return "DEBUG";
  23. }
  24. return "UNKNOWN";
  25. }
  26. /* Output the log to the console */
  27. void log_printf(int level, const char *fmt, ...)
  28. {
  29. va_list args;
  30. char logfmt[2048];
  31. char logtime[100];
  32. char *level_str;
  33. time_t rawtime;
  34. struct tm *timeinfo;
  35. if(level > min_log_level)
  36. {
  37. return;
  38. }
  39. time(&rawtime);
  40. timeinfo = localtime(&rawtime);
  41. strftime(logtime, 100, "%F %X", timeinfo);
  42. level_str = log_printable_level(level);
  43. if(fmt[strlen(fmt)-1] == '\n')
  44. {
  45. snprintf(logfmt, 2048, "%s: [%s]\t%s", logtime, level_str, fmt);
  46. }
  47. else
  48. {
  49. snprintf(logfmt, 2048, "%s: [%s]\t%s\n", logtime, level_str, fmt);
  50. }
  51. va_start(args, fmt);
  52. vfprintf(stderr, logfmt, args);
  53. va_end(args);
  54. }
  55. void log_test(void)
  56. {
  57. int i = 112;
  58. char *x = "test";
  59. log_printf(L_WARNING, "Testing");
  60. log_printf(L_ERROR, "Number stodwadziesciatrzy: %d", 123);
  61. d(beenthere);
  62. dd(i);
  63. dp(&i);
  64. ds(x);
  65. }