CPPMyth
Library to interoperate with MythTV server
debug.cpp
1 /*
2  * Copyright (C) 2014-2015 Jean-Luc Barriere
3  *
4  * This library is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as published
6  * by the Free Software Foundation; either version 3, or (at your option)
7  * 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
12  * GNU Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public License
15  * along with this library; see the file COPYING. If not, write to
16  * the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
17  * MA 02110-1301 USA
18  * http://www.gnu.org/copyleft/gpl.html
19  *
20  */
21 
22 #include "debug.h"
23 
24 #include <cstdlib>
25 #include <cstdarg>
26 #include <cstdio>
27 #include <cstring>
28 #include <ctype.h>
29 
30 #if defined(_MSC_VER) && _MSC_VER < 1900
31 #define snprintf _snprintf
32 #endif
33 
34 typedef struct
35 {
36  const char* name;
37  int cur_level;
38  void (*msg_callback)(int level, char* msg);
39 } debug_ctx_t;
40 
41 static debug_ctx_t debug_ctx = {LIBTAG, DBG_NONE, NULL};
42 
49 static inline void __dbg_setlevel(debug_ctx_t* ctx, int level)
50 {
51  if (ctx != NULL)
52  {
53  ctx->cur_level = level;
54  }
55 }
63 static inline void __dbg(debug_ctx_t* ctx, int level, const char* fmt, va_list ap)
64 {
65  if (ctx != NULL && level <= ctx->cur_level)
66  {
67  char msg[4096];
68  int len = snprintf(msg, sizeof (msg), "(%s)", ctx->name);
69  vsnprintf(msg + len, sizeof (msg) - len, fmt, ap);
70  if (ctx->msg_callback)
71  {
72  ctx->msg_callback(level, msg);
73  }
74  else
75  {
76  fwrite(msg, strlen(msg), 1, stderr);
77  }
78  }
79 }
80 
81 void NSROOT::DBGLevel(int l)
82 {
83  __dbg_setlevel(&debug_ctx, l);
84 }
85 
86 void NSROOT::DBGAll()
87 {
88  __dbg_setlevel(&debug_ctx, DBG_ALL);
89 }
90 
91 void NSROOT::DBGNone()
92 {
93  __dbg_setlevel(&debug_ctx, DBG_NONE);
94 }
95 
96 void NSROOT::DBG(int level, const char* fmt, ...)
97 {
98  va_list ap;
99 
100  va_start(ap, fmt);
101  __dbg(&debug_ctx, level, fmt, ap);
102  va_end(ap);
103 }
104 
105 void NSROOT::SetDBGMsgCallback(void (*msgcb)(int level, char*))
106 {
107  debug_ctx.msg_callback = msgcb;
108 }