-
-
Save joonhwan/3ef3cd28e7447516d2e0299634e917d1 to your computer and use it in GitHub Desktop.
Python: Use 'logging' module from C extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Python.h> | |
/***********************************************************/ | |
/* define logging function and logtypes for python.logging */ | |
/* by H.Dickten 2014 */ | |
/***********************************************************/ | |
enum logtypes {info, warning, error, debug}; | |
static void log_msg(int type, char *msg) | |
{ | |
static PyObject *logging = NULL; | |
static PyObject *string = NULL; | |
// import logging module on demand | |
if (logging == NULL){ | |
logging = PyImport_ImportModuleNoBlock("logging"); | |
if (logging == NULL) | |
PyErr_SetString(PyExc_ImportError, | |
"Could not import module 'logging'"); | |
} | |
// build msg-string | |
string = Py_BuildValue("s", msg); | |
// call function depending on loglevel | |
switch (type) | |
{ | |
case info: | |
PyObject_CallMethod(logging, "info", "O", string); | |
break; | |
case warning: | |
PyObject_CallMethod(logging, "warn", "O", string); | |
break; | |
case error: | |
PyObject_CallMethod(logging, "error", "O", string); | |
break; | |
case debug: | |
PyObject_CallMethod(logging, "debug", "O", string); | |
break; | |
} | |
Py_DECREF(string); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment