'g_log_structured not showing in system journal

I'm attempting to use g_log_structured to output messages from GLib to the Linux journal, but the messages aren't appearing.

#define G_LOG_USE_STRUCTURED
#include <glib-2.0/glib.h>
#include <stdio.h>

/* Compile command
  gcc mysource.c -lglib-2.0 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include
*/

int main(int argc, char *argv[]) {
    g_log_structured (G_LOG_DOMAIN,
                  G_LOG_LEVEL_INFO,
                  "CODE_FILE", "mysource.c",
                  "CODE_LINE", 312,
                  "MESSSAGE_ID", "123456",
                  "MESSAGE", "You have %d eggs", 12 + 2);
    return 0;
}

After running the program, I scan the journal with journalctl, but I can't find my message. What am I messing?



Solution 1:[1]

"Structured logging" and "logging to the journal" are 2 similar but different concepts.

On hand, you can do structured logging to several output streams: a file for example (which writes a CSV), or to stdout (where you might colorize certain fields). This is indeed done by defining G_LOG_USE_STRUCTURED and using g_log_structured()

On the other hand, you need some kind of callback to handle what should happen whenever the application logs a structured message. This is what we call a GLogWriterFunc. This callback can be set by issuing g_log_set_writer_func(). GLib provides a few such log writer callbacks by default since they are so common: g_log_writer_standard_streams, which writes to stdout/stderr and g_log_writer_journald, which writes to journald.

In other words, if you want to unconditionally write to the journal, you need to call the following before logging any message:

int main(int argc, char *argv[]) {
    /* You can of course write your own GLogWriterFunc and use that here */
    g_log_set_writer_func (g_log_writer_journald, NULL, NULL);

    /* The following log message will go to journald */
    g_log_structured (G_LOG_DOMAIN,
                  G_LOG_LEVEL_INFO,
                  "CODE_FILE", "mysource.c",
                  "CODE_LINE", 312,
                  "MESSSAGE_ID", "123456",
                  "MESSAGE", "You have %d eggs", 12 + 2);
    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1