enet_logging.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #ifndef ENET_LOGGING_H
  2. #define ENET_LOGGING_H
  3. #include <stdarg.h>
  4. #include <stdio.h>
  5. #if __APPLE__
  6. #include <TargetConditionals.h>
  7. #endif
  8. // TODO: Make better filenames; ie. enet_log.pid.txt
  9. #define ENET_LOG_FILE "enet_log.txt"
  10. static FILE *enet_log_fp = NULL;
  11. enum enet_log_type
  12. {
  13. ENET_LOG_TYPE_TRACE,
  14. ENET_LOG_TYPE_ERROR,
  15. };
  16. static const char *const enet_log_type_names[] = {
  17. [ENET_LOG_TYPE_TRACE] = "TRACE",
  18. [ENET_LOG_TYPE_ERROR] = "ERROR",
  19. };
  20. #if ENET_DEBUG
  21. # define ENET_LOG_TRACE(...) enet_log(ENET_LOG_TYPE_TRACE, __FUNCTION__, __LINE__, __VA_ARGS__)
  22. # define ENET_LOG_ERROR(...) enet_log(ENET_LOG_TYPE_ERROR, __FUNCTION__, __LINE__, __VA_ARGS__)
  23. #else
  24. # define ENET_LOG_TRACE(...) ((void)0)
  25. # define ENET_LOG_ERROR(...) ((void)0)
  26. #endif
  27. static inline void enet_log(enum enet_log_type type, const char *func, int line, const char *fmt, ...)
  28. {
  29. va_list args;
  30. time_t tstamp = time(NULL);
  31. struct tm *local_time = localtime(&tstamp);
  32. char time_buf[64];
  33. time_buf[strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", local_time)] = '\0';
  34. #if __APPLE__ && TARGET_OS_IPHONE
  35. // https://github.com/SoftwareGuy/ENet-CSharp/issues/15
  36. // iOS Debugging - File Access Permission (#blameApple)
  37. // Can't write to files without the file permission... so don't do that if we're on Apple.
  38. // Prefix
  39. printf("%s [%s] [%s:%d] ", time_buf, enet_log_type_names[type], func, line);
  40. va_start(args, fmt);
  41. vprintf(fmt, args);
  42. va_end(args);
  43. printf("\n");
  44. #else
  45. // Open the log file
  46. if (!enet_log_fp) enet_log_fp = fopen(ENET_LOG_FILE, "a");
  47. if (!enet_log_fp) return;
  48. fprintf(enet_log_fp, "%s [%s] [%s:%d] ", time_buf, enet_log_type_names[type], func, line);
  49. va_start(args, fmt);
  50. vfprintf(enet_log_fp, fmt, args);
  51. va_end(args);
  52. fprintf(enet_log_fp, "\n");
  53. fflush(enet_log_fp);
  54. #endif
  55. }
  56. #endif