debug.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*!
  2. * \file lib/gis/debug.c
  3. *
  4. * \brief GIS Library - Debug functions.
  5. *
  6. * (C) 2001-2012 by the GRASS Development Team
  7. *
  8. * This program is free software under the GNU General Public License
  9. * (>=v2). Read the file COPYING that comes with GRASS for details.
  10. *
  11. * \author GRASS GIS Development Team
  12. */
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <stdarg.h>
  17. #include <grass/gis.h>
  18. #include <grass/glocale.h>
  19. static int initialized;
  20. static int grass_debug_level;
  21. /**
  22. * \brief Initiate debugging.
  23. */
  24. void G_init_debug(void)
  25. {
  26. const char *lstr;
  27. if (G_is_initialized(&initialized))
  28. return;
  29. lstr = G_getenv_nofatal("DEBUG");
  30. if (lstr != NULL)
  31. grass_debug_level = atoi(lstr);
  32. else
  33. grass_debug_level = 0;
  34. G_initialize_done(&initialized);
  35. }
  36. /**
  37. * \brief Print debugging message.
  38. *
  39. * Print debugging message if environment variable GRASS_DEBUG_LEVEL
  40. * is set to level equal or greater
  41. *
  42. * Levels: (recommended levels)<br>
  43. * - 1 - message is printed once or twice per module<br>
  44. * - 2 - less interesting once-per-module messages,<br>
  45. * - 2 - library functions likely to be used once in a module<br>
  46. * - 3 - library functions likely to be called a few times in a module (<=10),<br>
  47. * - 3 - database opening and closing logistics<br>
  48. * - 4 - each row (raster) or line (vector) or database/column (DB),<br>
  49. * - 4 - each column/cat (DB)<br>
  50. * - 5 - each cell (raster) or point (vector) or cat/attribute (DB)
  51. *
  52. * \param[in] level level
  53. * \param[in] msg message
  54. * \return 0 on error
  55. * \return 1 on success
  56. */
  57. int G_debug(int level, const char *msg, ...)
  58. {
  59. char *filen;
  60. va_list ap;
  61. FILE *fd;
  62. G_init_debug();
  63. if (grass_debug_level >= level) {
  64. va_start(ap, msg);
  65. filen = getenv("GRASS_DEBUG_FILE");
  66. if (filen != NULL) {
  67. fd = fopen(filen, "a");
  68. if (!fd) {
  69. G_warning(_("Cannot open debug file '%s'"), filen);
  70. return 0;
  71. }
  72. }
  73. else {
  74. fd = stderr;
  75. }
  76. fprintf(fd, "D%d/%d: ", level, grass_debug_level);
  77. vfprintf(fd, msg, ap);
  78. fprintf(fd, "\n");
  79. fflush(fd);
  80. if (filen != NULL)
  81. fclose(fd);
  82. va_end(ap);
  83. }
  84. return 1;
  85. }