Thursday, February 21, 2013

Logging with Vala

How to send messages to syslog using Vala:

// log.vala

public static void main() {

    // Application Name (called 'domain' in Gspeak)
    string application_name = "MyTestApplication";

    // Log message
    string message = "This is a test message";

    // Log level - set to "Warning"
    GLib.LogLevelFlags glib_level       = GLib.LogLevelFlags.LEVEL_WARNING;
    int                posix_level      = Posix.LOG_WARNING; 

    // Print to stderr, not syslog or another log
    GLib.log( application_name, glib_level, message );

    // Log to syslog using the posix bindings
    // Posix.LOG_PID and Posix.LOG_USER are defined by Posix, not me.
    Posix.openlog(application_name, Posix.LOG_PID, Posix.LOG_USER);
    Posix.syslog(posix_level, message);

    return;
}

Compile using valac --pkg posix log.vala

No comments: