enet_logging.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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> // <-- Not needed?
  9. #include <asl.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. #if __APPLE__
  37. // Logging has changed, hopefully this will dump it into your Console.app
  38. // on macOS/iOS.
  39. char logStringBuf[512];
  40. // Prefix
  41. va_start(args, fmt);
  42. vsprintf(logStringBuf, fmt, args);
  43. asl_log(NULL, NULL, ASL_LEVEL_ERR, "%s", logStringBuf);
  44. va_end(args);
  45. #else
  46. // Timestamp
  47. time_buf[strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", local_time)] = '\0';
  48. // Open the log file
  49. if (!enet_log_fp) enet_log_fp = fopen(ENET_LOG_FILE, "a");
  50. if (!enet_log_fp) return;
  51. // Print the log into the file
  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. // Close the file
  58. fflush(enet_log_fp);
  59. #endif
  60. }
  61. #endif