enet_logging.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. // Debug
  22. #define ENET_LOG_TRACE(...) enet_log_to_file(ENET_LOG_TYPE_TRACE, __FUNCTION__, __LINE__, __VA_ARGS__)
  23. #define ENET_LOG_ERROR(...) enet_log_to_file(ENET_LOG_TYPE_ERROR, __FUNCTION__, __LINE__, __VA_ARGS__)
  24. static inline void enet_log_to_file(enum enet_log_type type, const char *func, int line, const char *fmt, ...)
  25. {
  26. va_list args;
  27. time_t tstamp = time(NULL);
  28. struct tm *local_time = localtime(&tstamp);
  29. char time_buf[64];
  30. time_buf[strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", local_time)] = '\0';
  31. #if __ANDROID__ || (__APPLE__ && TARGET_OS_IPHONE)
  32. // iOS Debugging - Sandboxed logging can't write file. This might extend even into Android!
  33. // Can't write to files without the file permission... so don't do that if we're on iOS/Android.
  34. // https://github.com/SoftwareGuy/ENet-CSharp/issues/15
  35. // Write the initial debug text to stdout.
  36. printf("%s [%s] [%s:%d] ", time_buf, enet_log_type_names[type], func, line);
  37. // Write our arguments and related stuff to stdout, then newline it.
  38. va_start(args, fmt);
  39. vprintf(fmt, args);
  40. va_end(args);
  41. printf("\n");
  42. // -- End logging for Android and Apple iOS -- //
  43. #else
  44. // Open the log file, and if we can't, then short-circuit.
  45. if (!enet_log_fp) enet_log_fp = fopen(ENET_LOG_FILE, "a");
  46. if (!enet_log_fp) return;
  47. // Write the initial debug text to buffer.
  48. fprintf(enet_log_fp, "%s [%s] [%s:%d] ", time_buf, enet_log_type_names[type], func, line);
  49. // Write our arguments and related stuff to buffer.
  50. va_start(args, fmt);
  51. vfprintf(enet_log_fp, fmt, args);
  52. va_end(args);
  53. // Write new line marker, then flush and wrap up.
  54. fprintf(enet_log_fp, "\n");
  55. fflush(enet_log_fp);
  56. // -- End logging for other platforms -- //
  57. #endif
  58. }
  59. #else
  60. // We are not building a debug library, stub the functions.
  61. #define ENET_LOG_TRACE(...) ((void)0)
  62. #define ENET_LOG_ERROR(...) ((void)0)
  63. #endif
  64. // end ifndef
  65. #endif