这不可能吗?
如果你真的想要,它仍然是,但根据用例,最好不要(见答案的第二部分)。
使用结构化日志实现自定义处理日志的新方法是 g_log_set_writer_func()。
例如:
#define G_LOG_USE_STRUCTURED
#include <glib.h>
static GLogWriterOutput
my_log_writer_func (GLogLevelFlags log_level,
const GLogField *fields,
size_t n_fields,
void *user_data)
{
if (log_level & G_LOG_LEVEL_CRITICAL) {
// Do something special with criticals
// For example purposes, let's just log it to stdout/stderr
return g_log_writer_standard_streams (log_level, fields, n_fields, user_data);
}
if (log_level & G_LOG_LEVEL_DEBUG) {
// This is not something you should do since it will make
// debugging harder, but let's just do it for example purposes:
// by returning G_LOG_WRITER_HANDLED without actually logging it,
// the log message will not be outputted anywhere
return G_LOG_WRITER_HANDLED;
}
// If you _really_ want to, you can still check on the GLib domain,
// as it will be set in one of the GLogFields
// Default case: use the default logger
return g_log_writer_default (log_level, fields, n_fields, user_data);
}
int
main (int argc, char *argv[])
{
g_log_set_writer_func (my_log_writer_func, NULL, NULL);
// Run your application
}
为什么 GLib 会放弃这样一个有用的功能?
正如我之前提到的,GLib 不难放弃对自定义日志实现的支持(请注意,这一切只有在您明确启用结构化日志记录时才有效)。我相信总体思路是越来越多的 GUI 应用程序从桌面(例如 GNOME Shell)或其他 UI 方式启动,因此要查看日志,您已经必须查看系统日志,例如使用 journalctl。
此时,当您可以使用系统日志时,在日志级别、日志域等上过滤日志消息会容易得多。它还避免了必须告诉用户“再次运行它,但现在使用这些随机环境变量,如G_MESSAGES_DEBUG=all”,因为他们可能不知道如何运行命令。它也可能是很难重现的东西,因此手头有调试日志会很有用。
journalctl 的一些示例命令是:(请注意,您可以轻松组合过滤器)
# Only show logs of the application with the given commandline name
$ journalctl _COMM=my-application-name
# Only show logs of your application with a given pid
$ journalctl _PID=$YOUR_APPS_PID
# Only show logs of your application with level WARNING or higher
$ journalctl -p warning
# Only show logs with with the given GLib domain
$ journalctl -f GLIB_DOMAIN=Gtk