enet_logging.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #ifndef ENET_LOGGING_H
  2. #define ENET_LOGGING_H
  3. #include <stdarg.h>
  4. #include <stdio.h>
  5. #define ENET_LOG_FILE "enet_log.txt"
  6. static FILE *enet_log_fp = NULL;
  7. enum enet_log_type
  8. {
  9. ENET_LOG_TYPE_TRACE,
  10. ENET_LOG_TYPE_ERROR,
  11. };
  12. static const char *const enet_log_type_names[] = {
  13. [ENET_LOG_TYPE_TRACE] = "TRACE",
  14. [ENET_LOG_TYPE_ERROR] = "ERROR",
  15. };
  16. #if ENET_DEBUG
  17. # define ENET_LOG_TRACE(...) enet_log(ENET_LOG_TYPE_TRACE, __FUNCTION__, __LINE__, __VA_ARGS__)
  18. # define ENET_LOG_ERROR(...) enet_log(ENET_LOG_TYPE_ERROR, __FUNCTION__, __LINE__, __VA_ARGS__)
  19. #else
  20. # define ENET_LOG_TRACE(...) ((void)0)
  21. # define ENET_LOG_ERROR(...) ((void)0)
  22. #endif
  23. static inline void enet_log(enum enet_log_type type, const char *func, int line, const char *fmt, ...)
  24. {
  25. if (!enet_log_fp) enet_log_fp = fopen(ENET_LOG_FILE, "a");
  26. if (!enet_log_fp) return;
  27. va_list args;
  28. time_t tstamp = time(NULL);
  29. struct tm *local_time = localtime(&tstamp);
  30. char time_buf[64];
  31. time_buf[strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", local_time)] = '\0';
  32. fprintf(enet_log_fp, "%s [%s] [%s:%d] ", time_buf, enet_log_type_names[type], func, line);
  33. va_start(args, fmt);
  34. vfprintf(enet_log_fp, fmt, args);
  35. va_end(args);
  36. fprintf(enet_log_fp, "\n");
  37. fflush(enet_log_fp);
  38. }
  39. #endif