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