Various modules solving daily C developer tasks
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
1.8 KiB

  1. /******************************************************************************
  2. *
  3. * Copyright (c) 2017-2019 by Löwenware Ltd
  4. * Please, refer LICENSE file for legal information
  5. *
  6. ******************************************************************************/
  7. /**
  8. * @file log.c
  9. * @author Ilja Kartašov <ik@lowenware.com>
  10. * @brief cStuff log module source file
  11. *
  12. * @see https://lowenware.com/
  13. */
  14. #include <time.h>
  15. #include "log.h"
  16. void
  17. cstuff_log_init(CStuffLog self, int level)
  18. {
  19. self->target = stderr;
  20. self->level = level;
  21. }
  22. void
  23. cstuff_log_release(CStuffLog self)
  24. {
  25. if (self->target != stderr)
  26. fclose(self->target);
  27. }
  28. CStuffRetcode
  29. cstuff_log_set_file(CStuffLog self, const char *filename)
  30. {
  31. FILE *fp;
  32. if (!(fp = fopen(filename, "a")))
  33. return CSTUFF_SYSCALL_ERROR;
  34. self->target = fp;
  35. return CSTUFF_SUCCESS;
  36. }
  37. int
  38. cstuff_log_printf(CStuffLog self, int level, const char *format, ...)
  39. {
  40. int result;
  41. va_list vl;
  42. va_start(vl, format);
  43. result = cstuff_log_vprintf(self, level, format, vl);
  44. va_end(vl);
  45. return result;
  46. }
  47. int
  48. cstuff_log_vprintf(CStuffLog self, int level, const char *format, va_list vl)
  49. {
  50. int result;
  51. if (self->level & level) {
  52. FILE *f = self->target;
  53. char *label;
  54. time_t rawtime;
  55. char strtime[32+1];
  56. struct tm timeinfo;
  57. time(&rawtime);
  58. localtime_r(&rawtime, &timeinfo);
  59. strftime(strtime, 32, "%F %T", &timeinfo);
  60. switch (level)
  61. {
  62. case CSTUFF_LOG_ERROR:
  63. label = "!!";
  64. break;
  65. case CSTUFF_LOG_ALERT:
  66. label = "~!";
  67. break;
  68. case CSTUFF_LOG_DEBUG:
  69. label = "**";
  70. break;
  71. default:
  72. label = "--";
  73. }
  74. result = fprintf(f, "%s %s ", strtime, label);
  75. result += vfprintf(f, format, vl);
  76. fputc('\n', f);
  77. result++;
  78. fflush(f);
  79. } else {
  80. result = 0;
  81. }
  82. return result;
  83. }