Skip to content

Instantly share code, notes, and snippets.

@joonhwan
Forked from hensing/python_logging.c
Created August 16, 2024 21:58
Show Gist options
  • Save joonhwan/3ef3cd28e7447516d2e0299634e917d1 to your computer and use it in GitHub Desktop.
Save joonhwan/3ef3cd28e7447516d2e0299634e917d1 to your computer and use it in GitHub Desktop.
Python: Use 'logging' module from C extension
#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