1 /*
2  * Copyright (C) 2014-2020 Paul Cercueil <paul@crapouillou.net>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  */
14 
15 #ifndef DEBUG_H
16 #define DEBUG_H
17 
18 #include <stdio.h>
19 #include <unistd.h>
20 
21 #define NOLOG_L 0
22 #define ERROR_L 1
23 #define WARNING_L 2
24 #define INFO_L 3
25 #define DEBUG_L 4
26 
27 #ifndef LOG_LEVEL
28 #define LOG_LEVEL INFO_L
29 #endif
30 
31 // -------------
32 
33 #ifndef COLOR_DEBUG
34 #define COLOR_DEBUG   "\e[0;32m"
35 #endif
36 #ifndef COLOR_WARNING
37 #define COLOR_WARNING "\e[01;35m"
38 #endif
39 #ifndef COLOR_ERROR
40 #define COLOR_ERROR   "\e[01;31m"
41 #endif
42 
43 #define COLOR_END "\e[0m"
44 
45 #if (LOG_LEVEL >= DEBUG_L)
46 # ifdef COLOR_DEBUG
47 #  define pr_debug(str, ...) do {					\
48 	if (isatty(STDOUT_FILENO))					\
49 		fprintf(stdout, COLOR_DEBUG "DEBUG: " str COLOR_END,	\
50 			##__VA_ARGS__);					\
51 	else								\
52 		fprintf(stdout, "DEBUG: " str, ##__VA_ARGS__);		\
53 	} while (0)
54 # else
55 #  define pr_debug(...) \
56     fprintf(stdout, "DEBUG: " __VA_ARGS__)
57 # endif
58 #else
59 #define pr_debug(...)
60 #endif
61 
62 #if (LOG_LEVEL >= INFO_L)
63 # ifdef COLOR_INFO
64 #  define pr_info(str, ...) \
65     fprintf(stdout, COLOR_INFO str COLOR_END, ##__VA_ARGS__)
66 # else
67 #  define pr_info(...) \
68     fprintf(stdout, __VA_ARGS__)
69 # endif
70 #else
71 #define pr_info(...)
72 #endif
73 
74 #if (LOG_LEVEL >= WARNING_L)
75 # ifdef COLOR_WARNING
76 #  define pr_warn(str, ...) do {					\
77 	if (isatty(STDERR_FILENO))					\
78 		fprintf(stderr, COLOR_WARNING "WARNING: " str COLOR_END,\
79 			##__VA_ARGS__);					\
80 	else								\
81 		fprintf(stderr, "WARNING: " str, ##__VA_ARGS__);	\
82 	} while (0)
83 # else
84 #  define pr_warn(...) \
85     fprintf(stderr, "WARNING: " __VA_ARGS__)
86 # endif
87 #else
88 #define pr_warn(...)
89 #endif
90 
91 #if (LOG_LEVEL >= ERROR_L)
92 # ifdef COLOR_ERROR
93 #  define pr_err(str, ...) do {						\
94 	if (isatty(STDERR_FILENO))					\
95 		fprintf(stderr, COLOR_ERROR "ERROR: " str COLOR_END,	\
96 			##__VA_ARGS__);					\
97 	else								\
98 		fprintf(stderr, "ERROR: " str, ##__VA_ARGS__);		\
99 	} while (0)
100 # else
101 #  define pr_err(...) \
102     fprintf(stderr, "ERROR: " __VA_ARGS__)
103 # endif
104 #else
105 #define pr_err(...)
106 #endif
107 
108 #endif
109