Last active
August 16, 2024 21:58
-
-
Save hensing/0db3f8e3a99590006368 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); | |
} |
happy to help :)
Can we do the reverse, use C logging in python using ctypes? Right now I am facing segmentation issues.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice. great hint to me. thanks 👍