debug.c 2.1 KB

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