debug.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /* PDCurses */
  2. #include <curspriv.h>
  3. /*man-start**************************************************************
  4. debug
  5. -----
  6. ### Synopsis
  7. void traceon(void);
  8. void traceoff(void);
  9. void PDC_debug(const char *, ...);
  10. ### Description
  11. traceon() and traceoff() toggle the recording of debugging
  12. information to the file "trace". Although not standard, similar
  13. functions are in some other curses implementations.
  14. PDC_debug() is the function that writes to the file, based on whether
  15. traceon() has been called. It's used from the PDC_LOG() macro.
  16. The environment variable PDC_TRACE_FLUSH controls whether the trace
  17. file contents are fflushed after each write. The default is not. Set
  18. it to enable this (may affect performance).
  19. ### Portability
  20. X/Open ncurses NetBSD
  21. traceon - - -
  22. traceoff - - -
  23. PDC_debug - - -
  24. **man-end****************************************************************/
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <sys/types.h>
  28. #include <time.h>
  29. static bool want_fflush = FALSE;
  30. void PDC_debug(const char *fmt, ...)
  31. {
  32. va_list args;
  33. char hms[9];
  34. time_t now;
  35. if (!SP || !SP->dbfp)
  36. return;
  37. time(&now);
  38. strftime(hms, 9, "%H:%M:%S", localtime(&now));
  39. fprintf(SP->dbfp, "At: %8.8ld - %s ", (long) clock(), hms);
  40. va_start(args, fmt);
  41. vfprintf(SP->dbfp, fmt, args);
  42. va_end(args);
  43. /* If you are crashing and losing debugging information, enable this
  44. by setting the environment variable PDC_TRACE_FLUSH. This may
  45. impact performance. */
  46. if (want_fflush)
  47. fflush(SP->dbfp);
  48. /* If with PDC_TRACE_FLUSH enabled you are still losing logging in
  49. crashes, you may need to add a platform-dependent mechanism to
  50. flush the OS buffers as well (such as fsync() on POSIX) -- but
  51. expect terrible performance. */
  52. }
  53. void traceon(void)
  54. {
  55. if (!SP)
  56. return;
  57. if (SP->dbfp)
  58. fclose(SP->dbfp);
  59. /* open debug log file append */
  60. SP->dbfp = fopen("trace", "a");
  61. if (!SP->dbfp)
  62. {
  63. fprintf(stderr, "PDC_debug(): Unable to open debug log file\n");
  64. return;
  65. }
  66. if (getenv("PDC_TRACE_FLUSH"))
  67. want_fflush = TRUE;
  68. PDC_LOG(("traceon() - called\n"));
  69. }
  70. void traceoff(void)
  71. {
  72. if (!SP || !SP->dbfp)
  73. return;
  74. PDC_LOG(("traceoff() - called\n"));
  75. fclose(SP->dbfp);
  76. SP->dbfp = NULL;
  77. want_fflush = FALSE;
  78. }