enet_logging.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #ifndef ENET_LOGGING_H
  2. #define ENET_LOGGING_H
  3. // Include basic things used for our logging facility.
  4. #include <stdarg.h>
  5. #include <stdio.h>
  6. // Apple Specific things.
  7. #if __APPLE__
  8. #include <TargetConditionals.h>
  9. #include <CoreFoundation/CoreFoundation.h>
  10. #endif
  11. // TODO: Make better filenames; ie. enet_log.pid.txt
  12. #define ENET_LOG_FILE "enet_debug.log"
  13. static FILE *enet_log_fp = NULL;
  14. enum enet_log_type
  15. {
  16. ENET_LOG_TYPE_TRACE,
  17. ENET_LOG_TYPE_ERROR,
  18. };
  19. static const char *const enet_log_type_names[] = {
  20. [ENET_LOG_TYPE_TRACE] = "TRACE",
  21. [ENET_LOG_TYPE_ERROR] = "ERROR",
  22. };
  23. #if ENET_DEBUG
  24. # define ENET_LOG_TRACE(...) enet_log(ENET_LOG_TYPE_TRACE, __FUNCTION__, __LINE__, __VA_ARGS__)
  25. # define ENET_LOG_ERROR(...) enet_log(ENET_LOG_TYPE_ERROR, __FUNCTION__, __LINE__, __VA_ARGS__)
  26. #else
  27. # define ENET_LOG_TRACE(...) ((void)0)
  28. # define ENET_LOG_ERROR(...) ((void)0)
  29. #endif
  30. static inline void enet_log(enum enet_log_type type, const char *func, int line, const char *fmt, ...)
  31. {
  32. va_list args;
  33. time_t tstamp = time(NULL);
  34. struct tm *local_time = localtime(&tstamp);
  35. char time_buf[64];
  36. time_buf[strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", local_time)] = '\0';
  37. #if __APPLE__
  38. // Logging has changed, hopefully this will dump it into your Console.app
  39. // on macOS/iOS.
  40. // Prefix
  41. printf("Enet: %s [%s] [%s:%d] ", time_buf, enet_log_type_names[type], func, line);
  42. va_start(args, fmt);
  43. // TESTING
  44. AppleNSLog(fmt, args);
  45. // vprintf(fmt, args);
  46. va_end(args);
  47. printf("\n");
  48. #else
  49. // Open the log file
  50. if (!enet_log_fp) enet_log_fp = fopen(ENET_LOG_FILE, "a");
  51. if (!enet_log_fp) return;
  52. fprintf(enet_log_fp, "%s [%s] [%s:%d] ", time_buf, enet_log_type_names[type], func, line);
  53. va_start(args, fmt);
  54. vfprintf(enet_log_fp, fmt, args);
  55. va_end(args);
  56. fprintf(enet_log_fp, "\n");
  57. fflush(enet_log_fp);
  58. #endif
  59. }
  60. #endif