logger.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * 2D Physic Engine
  3. * logger.cpp: The logger
  4. * Based on pikuma.com Learn Game Physics Engine Programming course.
  5. * Copyright (c) 2021-2022 986-Studio. All rights reserved.
  6. *
  7. * Created by Manoël Trapier on 11/02/2021.
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <stdint.h>
  12. #include <stdarg.h>
  13. #include <time.h>
  14. #include <logger.h>
  15. typedef struct logData
  16. {
  17. char name[7];
  18. uint8_t colour;
  19. } logData;
  20. static logData dataTable[] =
  21. {
  22. [LOG_LOG] = { "LOG", 32 },
  23. [LOG_ERROR] = { "ERROR", 31 },
  24. [LOG_WARNING] = { "WARN", 33 },
  25. [LOG_INFO] = { "INFO", 36 },
  26. [LOG_CRITICAL] = { "CRITIC", 101 },
  27. [LOG_DEBUG] = { "DEBUG", 35 },
  28. };
  29. static void addLog(LogType type, const char *message, va_list params)
  30. {
  31. time_t curtime = time(NULL);
  32. char buf[30];
  33. struct tm *p = localtime(&curtime);
  34. int typeColour = dataTable[type].colour;
  35. const char *typeName = dataTable[type].name;
  36. strftime(buf, 38, "%d-%b-%Y %H:%M:%S", p);
  37. fprintf(stderr, "\x1B[%d;1m%-6s | %-20s - ", typeColour, typeName, buf);
  38. vfprintf(stderr, message, params);
  39. fprintf(stderr, "\x1B[0m\n");
  40. }
  41. void logger::log(const char *message, ...)
  42. {
  43. va_list list;
  44. va_start(list, message);
  45. addLog(LOG_LOG, message, list);
  46. va_end(list);
  47. }
  48. void logger::error(const char *message, ...)
  49. {
  50. va_list list;
  51. va_start(list, message);
  52. addLog(LOG_ERROR, message, list);
  53. va_end(list);
  54. }
  55. void logger::warning(const char *message, ...)
  56. {
  57. va_list list;
  58. va_start(list, message);
  59. addLog(LOG_WARNING, message, list);
  60. va_end(list);
  61. }
  62. void logger::info(const char *message, ...)
  63. {
  64. va_list list;
  65. va_start(list, message);
  66. addLog(LOG_INFO, message, list);
  67. va_end(list);
  68. }
  69. void logger::critical(const char *message, ...)
  70. {
  71. va_list list;
  72. va_start(list, message);
  73. addLog(LOG_CRITICAL, message, list);
  74. va_end(list);
  75. }
  76. void logger::debug(const char *message, ...)
  77. {
  78. va_list list;
  79. va_start(list, message);
  80. addLog(LOG_DEBUG, message, list);
  81. va_end(list);
  82. }