Showing posts with label logging. Show all posts
Showing posts with label logging. Show all posts

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

Thursday, January 17, 2013

Logging in Python 3

Here is one way to set up proper logging in Python.

This sample script sends some messages to syslog and others to a different logfile based upon their priority.


#!/usr/bin/python3

# Import the Standard Library modules we need
import logging
import logging.handlers

def set_up_logging():

    # File handler for /var/log/some.log
    serverlog = logging.FileHandler('/var/log/some.log')
    serverlog.setLevel(logging.DEBUG)
    serverlog.setFormatter(logging.Formatter(
        '%(asctime)s %(pathname)s [%(process)d]: %(levelname)s %(message)s'))

    # Syslog handler
    syslog = logging.handlers.SysLogHandler(address='/dev/log')
    syslog.setLevel(logging.WARNING)
    syslog.setFormatter(logging.Formatter(
        '%(pathname)s [%(process)d]: %(levelname)s %(message)s'))

    # Combined logger used elsewhere in the script
    logger = logging.getLogger('wbs-server-log')
    logger.setLevel(logging.DEBUG)
    logger.addHandler(serverlog)
    logger.addHandler(syslog)

    return logger

logger = set_up_logging()
logger.debug('This message should go to the log file')
logger.info('So should this')
logger.warning('And this, too')