glib学习1-一个简单的例子与g_log

时间:2022-07-31 23:56:48
1. hello.c
#include <glib.h>
#include <locale.h>
GMainLoop* loop;
gint counter = 10;
gboolean callback(gpointer arg)
{
    g_print("hello world\n");
	g_message("中文");
	fflush();
    if(--counter ==0){
        g_print("\n");
        //退出循环
        g_main_loop_quit(loop);
        //注销定时器
        return FALSE;
    }
    //定时器继续运行
    return TRUE;
}
int main(int argc, char* argv[])
{
    setlocale (LC_ALL, "");/*将程序的locale设置成与console的一致*/
    //g_thread_init是必需的,GMainLoop需要gthread库的支持。
    if(g_thread_supported() == 0)
        g_thread_init(NULL);
    //创建一个循环体,先不管参数的意思。
    g_print("g_main_loop_new\n");
    loop = g_main_loop_new(NULL, FALSE);
   //增加一个定时器,100毫秒运行一次callback
    g_timeout_add(1000,callback,NULL);
    g_print("g_main_loop_run\n");
    g_main_loop_run(loop);
    g_print("g_main_loop_unref\n");
    g_main_loop_unref(loop);
    return 0;
}


编译:

$ gcc main.c `pkg-config --cflags --libs glib-2.0 gthread-2.0` hello.c -o hello
注意不是单引号,是反引号,左上角那个键!
2. glib中log的等级分为以下几种,可以根据需要来打印不同等级的log信息
      

G_LOG_FLAG_RECURSION

internal flag

G_LOG_FLAG_FATAL

internal flag

G_LOG_LEVEL_ERROR

log level for errors, see g_error(). This level is also used for messages produced by g_assert().

G_LOG_LEVEL_CRITICAL

log level for critical messages, see g_critical(). This level is also used for messages produced by g_return_if_fail() and g_return_val_if_fail().

G_LOG_LEVEL_WARNING

log level for warnings, see g_warning()

G_LOG_LEVEL_MESSAGE

log level for messages, see g_message()

G_LOG_LEVEL_INFO

log level for informational messages

G_LOG_LEVEL_DEBUG

log level for debug messages, see g_debug()

G_LOG_LEVEL_MASK

a mask including all log levels
typedef enum {
  /* log flags */
  G_LOG_FLAG_RECURSION          = 1 << 0,
  G_LOG_FLAG_FATAL              = 1 << 1,

  /* GLib log levels */
  G_LOG_LEVEL_ERROR             = 1 << 2,       /* always fatal */
  G_LOG_LEVEL_CRITICAL          = 1 << 3,
  G_LOG_LEVEL_WARNING           = 1 << 4,
  G_LOG_LEVEL_MESSAGE           = 1 << 5,
  G_LOG_LEVEL_INFO              = 1 << 6,
  G_LOG_LEVEL_DEBUG             = 1 << 7,

  G_LOG_LEVEL_MASK              = ~(G_LOG_FLAG_RECURSION | G_LOG_FLAG_FATAL)
} GLogLevelFlags;

具体用法为:
#include <glib.h>
void    none_log(const gchar   *log_domain,
    GLogLevelFlags log_level,
    const gchar   *message,
    gpointer       user_data)
{
    return;
}
 
int main(int argc, char* argv[])
{
    GMainLoop* main_loop = g_main_loop_new(NULL, FALSE);
 
    g_log_set_handler(NULL, G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATA, none_log, NULL); //将红色字体设置为响应的等级就ok了
 
    g_debug("%s:%d", __func__, __LINE__);
    g_warning("%s:%d", __func__, __LINE__);
 
    g_main_loop_run(main_loop);
 
    return 0;
}

但是,经测试,glib 2.32.2之后,g_debug不能用了,即使设置环境变量export G_MESSAGE_DEBUG=all。只能使用g_message,g_critical,g_warning等函数。