编写其他工程,可以借鉴。
#include
#include
#include
#define spice_info(format, ...) G_STMT_START { \
spice_log(G_LOG_LEVEL_INFO, __FUNCTION__, "" format, ## __VA_ARGS__); \
} G_STMT_END
#define spice_debug(format, ...) G_STMT_START { \
spice_log(G_LOG_LEVEL_DEBUG, __FUNCTION__, "" format, ## __VA_ARGS__); \
} G_STMT_END
#define spice_warning(format, ...) G_STMT_START { \
spice_log(G_LOG_LEVEL_WARNING, __FUNCTION__, "" format, ## __VA_ARGS__); \
} G_STMT_END
#define spice_critical(format, ...) G_STMT_START { \
spice_log(G_LOG_LEVEL_CRITICAL, __FUNCTION__, "" format, ## __VA_ARGS__); \
} G_STMT_END
#define spice_error(format, ...) G_STMT_START { \
spice_log(G_LOG_LEVEL_ERROR, __FUNCTION__, "" format, ## __VA_ARGS__); \
} G_STMT_END
static int glib_debug_level = INT_MAX;
static int abort_mask = 0;
static void spice_logv(const char *log_domain,
GLogLevelFlags log_level,
const char *function,
const char *format,
va_list args)
{
GString *log_msg;
if ((log_level & G_LOG_LEVEL_MASK) > glib_debug_level) {
return; // do not print anything
}
log_msg = g_string_new(NULL);
if ( function) {
g_string_append_printf(log_msg, "%s: ", function);
}
if (format) {
g_string_append_vprintf(log_msg, format, args);
}
g_log(log_domain, log_level, "%s", log_msg->str);
g_string_free(log_msg, TRUE);
/*
if ((abort_mask & log_level) != 0) {
spice_backtrace();
abort();
}
*/
}
void spice_log(GLogLevelFlags log_level,
const char *function,
const char *format,
...)
{
va_list args;
va_start (args, format);
spice_logv (G_LOG_DOMAIN, log_level, function, format, args);
va_end (args);
}
int main()
{
spice_info("this is info");
spice_debug("this is debug");
spice_warning("this is warning");
spice_critical("this is critical");
//spice_error("this is error");
return 0;
}
编译&运行结果
[root@net test]# gcc log.c -o log -pthread -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include -lglib-2.0
[root@allinone01 test]# ./log
* (process:15224): WARNING *: main: this is warning
* (process:15224): CRITICAL *: main: this is critical
[root@net test]#