Skip to content

Instantly share code, notes, and snippets.

@hensing
Last active May 20, 2024 06:55
Show Gist options
  • Save hensing/0db3f8e3a99590006368 to your computer and use it in GitHub Desktop.
Save hensing/0db3f8e3a99590006368 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);
}
@joonhwan
Copy link

nice. great hint to me. thanks 👍

@hensing
Copy link
Author

hensing commented Sep 16, 2021

happy to help :)

@saudzahirr
Copy link

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