Skip to content

Instantly share code, notes, and snippets.

@machinaut
Created September 28, 2016 16:07
Show Gist options
  • Save machinaut/f35ffea92a16c2b44cff4e9ac55678af to your computer and use it in GitHub Desktop.
Save machinaut/f35ffea92a16c2b44cff4e9ac55678af to your computer and use it in GitHub Desktop.
printf() style output through python's logger in python c extension
// logger.c - hook into python's logging module
#include <Python.h>
#include <stdarg.h>
#include "logger.h"
static PyObject *logger;
// logger = logging.getLogger('libvncdriver')
int logger_init(void) {
PyObject *logging_module = NULL;
// First-time import the logging module, or throw an exception trying
if (NULL == logger) {
logging_module = PyImport_ImportModuleNoBlock("logging");
if (NULL == logging_module) {
PyErr_SetString(PyExc_ImportError, "Failed to import 'logging' module");
return -1;
}
}
// logging.basicConfig()
PyObject_CallMethod(logging_module, "basicConfig", NULL);
// logger = logging.getLogger('libvncdriver')
logger = PyObject_CallMethod(logging_module, "getLogger", "s", "libvncdriver");
// logger.setLevel(INFO)
PyObject_CallMethod(logger, "setLevel", "i", INFO);
return 0;
}
void logger_str(logging_level_e level, const char *format, ...) {
char buf[1024]; // Should be enough for anybody...
va_list(args);
va_start(args, format);
vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
PyObject_CallMethod(logger, "log", "is", level, buf);
}
// logger.h - hook into python's logging module
#include <stdarg.h>
// https://docs.python.org/2.7/library/logging.html#logging-levels
typedef enum {
NOTSET = 0,
DEBUG = 10,
INFO = 20,
WARNING = 30,
ERROR = 40,
CRITICAL = 50,
} logging_level_e;
// Call once to initialize and setup logging
// Returns negative on failure
int logger_init(void);
// Use the "logging" python module to log a string (printf-style)
void logger_str(logging_level_e level, const char *format, ...);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment