enet_logging.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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_debug.log"
  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_to_file(ENET_LOG_TYPE_TRACE, __FUNCTION__, __LINE__, __VA_ARGS__)
  22. # define ENET_LOG_ERROR(...) enet_log_to_file(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_to_file(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 __ANDROID__ || (__APPLE__ && TARGET_OS_IPHONE)
  35. // iOS Debugging - Sandboxed logging can't write file. This might extend even into Android!
  36. // Can't write to files without the file permission... so don't do that if we're on Apple.
  37. // https://github.com/SoftwareGuy/ENet-CSharp/issues/15
  38. printf("%s [%s] [%s:%d] ", time_buf, enet_log_type_names[type], func, line);
  39. va_start(args, fmt);
  40. vprintf(fmt, args);
  41. va_end(args);
  42. printf("\n");
  43. // -- End logging for Android and Apple iOS -- //
  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. // -- End logging for other platforms -- //
  55. #endif
  56. }
  57. #endif