11. Logging and Frames¶
This chapter describes how to use the Python logging interface for C and how to access Python frames from C.
11.1. Logging From C¶
This presents a recipe for using the Python logging module in C.
Many thanks to nnathan for starting this.
We import the module and define C equivalent logging functions that are compatible with the *printf family.
11.1.1. Logging C Declarations¶
First define the log levels, #define is used so the that switch case does not issue a compile time non-const error:
1#define PPY_SSIZE_T_CLEAN
2#include <Python.h>
3/* For va_start, va_end */
4#include <stdarg.h>
5
6/* logging levels defined by logging module
7 * From: https://docs.python.org/3/library/logging.html#logging-levels */
8#define LOGGING_DEBUG 10
9#define LOGGING_INFO 20
10#define LOGGING_WARNING 30
11#define LOGGING_ERROR 40
12#define LOGGING_CRITICAL 50
13#define LOGGING_EXCEPTION 60
11.1.2. Logging C Globals¶
Then two globals, the first is the imported logging module, the next the current logger:
/* This modules globals */
static PyObject *g_logging_module = NULL; /* Initialise by PyInit_cLogging() below. */
static PyObject *g_logger = NULL;
11.1.3. Logging C Functions¶
Now a function to get a logger object from the logging module:
1static PyObject *py_get_logger(char *logger_name) {
2 assert(g_logging_module);
3 PyObject *logger = NULL;
4
5 logger = PyObject_CallMethod(g_logging_module, "getLogger", "s", logger_name);
6 if (logger == NULL) {
7 const char *err_msg = "failed to call logging.getLogger";
8 PyErr_SetString(PyExc_RuntimeError, err_msg);
9 }
10 /*
11 fprintf(stdout, "%s()#%d logger=0x%p\n", __FUNCTION__, __LINE__, (void *)logger);
12 */
13 return logger;
14}
Now the main interface to logging function:
1static PyObject *
2py_log_msg(int log_level, char *printf_fmt, ...) {
3 assert(g_logger);
4 assert(!PyErr_Occurred());
5 PyObject *log_msg = NULL;
6 PyObject *ret = NULL;
7 va_list fmt_args;
8
9 va_start(fmt_args, printf_fmt);
10 log_msg = PyUnicode_FromFormatV(printf_fmt, fmt_args);
11 va_end(fmt_args);
12
13 if (log_msg == NULL) {
14 /* fail. */
15 ret = PyObject_CallMethod(
16 g_logger,
17 "critical",
18 "O", "Unable to create log message."
19 );
20 } else {
21 /* call function depending on loglevel */
22 switch (log_level) {
23 case LOGGING_DEBUG:
24 ret = PyObject_CallMethod(g_logger, "debug", "O", log_msg);
25 break;
26 case LOGGING_INFO:
27 ret = PyObject_CallMethod(g_logger, "info", "O", log_msg);
28 break;
29 case LOGGING_WARNING:
30 ret = PyObject_CallMethod(g_logger, "warning", "O", log_msg);
31 break;
32 case LOGGING_ERROR:
33 ret = PyObject_CallMethod(g_logger, "error", "O", log_msg);
34 break;
35 case LOGGING_CRITICAL:
36 ret = PyObject_CallMethod(g_logger, "critical", "O", log_msg);
37 break;
38 default:
39 ret = PyObject_CallMethod(g_logger, "critical", "O", log_msg);
40 break;
41 }
42 assert(!PyErr_Occurred());
43 }
44 Py_DECREF(log_msg);
45 return ret;
46}
A function to set a log level:
1static PyObject *
2py_log_set_level(PyObject *Py_UNUSED(module), PyObject *args) {
3 assert(g_logger);
4 PyObject *py_log_level;
5
6 if (!PyArg_ParseTuple(args, "O", &py_log_level)) {
7 return NULL;
8 }
9 return PyObject_CallMethod(g_logger, "setLevel", "O", py_log_level);
10}
And the main function to log a message:
1static PyObject *
2py_log_message(PyObject *Py_UNUSED(module), PyObject *args) {
3 int log_level;
4 char *message;
5
6 if (!PyArg_ParseTuple(args, "iz", &log_level, &message)) {
7 return NULL;
8 }
9 return py_log_msg(log_level, "%s", message);
10}
11.1.4. cLogging Module¶
Setup the module functions:
1static PyMethodDef logging_methods[] = {
2 /* ... */
3 {
4 "py_log_set_level",
5 (PyCFunction) py_log_set_level,
6 METH_VARARGS,
7 "Set the logging level."
8 },
9 {
10 "log",
11 (PyCFunction) py_log_message,
12 METH_VARARGS,
13 "Log a message."
14 },
15 /* ... */
16 {NULL, NULL, 0, NULL} /* Sentinel */
17};
The module definition:
static PyModuleDef cLogging = {
PyModuleDef_HEAD_INIT,
.m_name = "cLogging",
.m_doc = "Logging mmodule.",
.m_size = -1,
.m_methods = logging_methods,
};
The module initialisation, this is where the logging module is imported with PyImport_ImportModule():
1PyMODINIT_FUNC PyInit_cLogging(void) {
2 PyObject *m = PyModule_Create(&cLogging);
3 if (! m) {
4 goto except;
5 }
6 g_logging_import = PyImport_ImportModule("logging");
7 if (!g_logging_import) {
8 const char *err_msg = "failed to import 'logging'";
9 PyErr_SetString(PyExc_ImportError, err_msg);
10 goto except;
11 }
12 g_logger = py_get_logger("cLogging");
13 if (!g_logger) {
14 goto except;
15 }
16 /* Adding module globals */
17 /* logging levels defined by logging module.
18 * Note: In Python logging FATAL = CRITICAL */
19 if (PyModule_AddIntConstant(m, "INFO", LOGGING_INFO)) {
20 goto except;
21 }
22 if (PyModule_AddIntConstant(m, "WARNING", LOGGING_WARNING)) {
23 goto except;
24 }
25 if (PyModule_AddIntConstant(m, "ERROR", LOGGING_ERROR)) {
26 goto except;
27 }
28 if (PyModule_AddIntConstant(m, "FATAL", LOGGING_FATAL)) {
29 goto except;
30 }
31 if (PyModule_AddIntConstant(m, "CRITICAL", LOGGING_FATAL)) {
32 goto except;
33 }
34 if (PyModule_AddIntConstant(m, "DEBUG", LOGGING_DEBUG)) {
35 goto except;
36 }
37 if (PyModule_AddIntConstant(m, "EXCEPTION", LOGGING_EXCEPTION)) {
38 goto except;
39 }
40
41 goto finally;
42except:
43 /* abnormal cleanup */
44 /* cleanup logger references */
45 Py_XDECREF(g_logging_import);
46 Py_XDECREF(g_logger);
47finally:
48 return m;
49}
Create in the setup.py:
Extension(name=f"{PACKAGE_NAME}.Logging.cLogging",
include_dirs=[],
sources=["src/cpy/Logging/cLogging.c", ],
extra_compile_args=extra_compile_args_c,
language='c',
),
And run python setup.py develop.
11.1.5. Using and Testing¶
11.1.5.1. Using From C¶
To simply use the interface defined in the above function, use it like the printf family of functions:
py_log_msg(WARNING, "error code: %d", 10);
11.1.5.2. Using From Python¶
from cPyExtPatt.Logging import cLogging
cLogging.log(cLogging.ERROR, "Test log message")
There are various tests in tests/unit/test_c_logging.py.
As pytest swallows logging messages there is a main() function in that script so you can run it from the command
line:
1def main():
2 logger.setLevel(logging.DEBUG)
3 logger.info('main')
4 logger.warning('Test warning message XXXX')
5 logger.debug('Test debug message XXXX')
6 logger.info('_test_logging')
7 test_logging()
8 print()
9 print(cLogging)
10 print(dir(cLogging))
11 print()
12 logger.info('cLogging.log():')
13 cLogging.py_log_set_level(10)
14 cLogging.log(cLogging.ERROR, "cLogging.log(): Test log message")
15
16 return 0
17
18
19if __name__ == '__main__':
20 exit(main())
Here is an example output:
1$python tests/unit/test_c_logging.py
22025-03-07 11:49:23,994 7064 INFO main
32025-03-07 11:49:23,994 7064 WARNING Test warning message XXXX
42025-03-07 11:49:23,994 7064 DEBUG Test debug message XXXX
52025-03-07 11:49:23,994 7064 INFO _test_logging
62025-03-07 11:49:23,994 7064 WARNING Test warning message XXXX
72025-03-07 11:49:23,994 7064 DEBUG Test debug message XXXX
8
9<module 'cPyExtPatt.Logging.cLogging' from 'PythonExtensionPatterns/cPyExtPatt/Logging/cLogging.cpython-313-darwin.so'>
10['CRITICAL', 'DEBUG', 'ERROR', 'EXCEPTION', 'INFO', 'WARNING', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'c_file_line_function', 'log', 'py_file_line_function', 'py_log_set_level']
11
122025-03-07 11:49:23,994 7064 INFO cLogging.log():
132025-03-07 11:49:23,994 7064 ERROR cLogging.log(): Test log message
11.2. Frames¶
This describes how to extract the currently executing Python frame (or call stack if you wish).
11.2.1. The Python Frame¶
The crucial call is PyEval_GetFrame() that gets the current executing frame as a PyFrameObject. From Python 3.11 onwards the PyFrameObject has no public members instead there are many functions in the Frame API to extract the data we need. Prior to that we could extract tha data directly.
The example code is in src/cpy/Logging/cLogging.c.
1/**
2 * Returns a tuple of the file, line and function of the current Python frame.
3 * Returns (None, 0, None) on failure.
4 * @param _unused_module
5 * @return PyObject *, a tuple of three values.
6 */
7static PyObject *
8py_file_line_function(PyObject *Py_UNUSED(module)) {
9 const unsigned char *file_name = NULL;
10 const char *func_name = NULL;
11 int line_number = 0;
12
13 PyFrameObject *frame = PyEval_GetFrame();
14 if (frame) {
15 /* Get the file name. */
16#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 11
17 /* See:
18 * https://docs.python.org/3.11/whatsnew/3.11.html#pyframeobject-3-11-hiding
19 */
20 file_name = PyUnicode_1BYTE_DATA(PyFrame_GetCode(frame)->co_filename);
21#else
22 file_name = PyUnicode_1BYTE_DATA(frame->f_code->co_filename);
23#endif // PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 11
24 /* Get the line number. */
25 line_number = PyFrame_GetLineNumber(frame);
26 /* Get the function name. */
27#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 11
28 /* See:
29 * https://docs.python.org/3.11/whatsnew/3.11.html#pyframeobject-3-11-hiding
30 */
31 func_name = (const char *) PyUnicode_1BYTE_DATA(PyFrame_GetCode(frame)->co_name);
32#else
33 func_name = (const char *) PyUnicode_1BYTE_DATA(frame->f_code->co_name);
34#endif // PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 11
35 }
36 /* Build the return value. */
37 /* Use 'z' that makes Python None if the string is NULL. */
38 return Py_BuildValue("ziz", file_name, line_number, func_name);
39}
And this function is registered thus:
1static PyMethodDef logging_methods[] = {
2 /* ... */
3 {
4 "py_file_line_function",
5 (PyCFunction) py_file_line_function,
6 METH_NOARGS,
7 "Return the file, line and function name from the current Python frame."
8 },
9 /* ... */
10 {NULL, NULL, 0, NULL} /* Sentinel */
11};
And can be used thus (test code is in tests/unit/test_c_logging.py):
1from cPyExtPatt.Logging import cLogging
2
3def test_py_file_line_function_file():
4 file, _line, _function = cLogging.py_file_line_function()
5 assert file == __file__
6
7
8def test_py_file_line_function_line():
9 _file, line, _function = cLogging.py_file_line_function()
10 assert line == 50
11
12
13def test_py_file_line_function_function():
14 _file, _line, function = cLogging.py_file_line_function()
15 assert function == 'test_py_file_line_function_function'
11.2.2. The C “Frame”¶
It is also useful to be able to extract the C “frame” (actually the code location at compile time) and present that as the same kind of Python tuple.
A simple macro helps:
#define C_FILE_LINE_FUNCTION Py_BuildValue("sis", __FILE__, __LINE__, __FUNCTION__)
And is used thus:
static PyObject *
c_file_line_function(PyObject *Py_UNUSED(module)) {
return C_FILE_LINE_FUNCTION;
}
Teh function is registered thus:
1static PyMethodDef logging_methods[] = {
2 /* ... */
3 {
4 "c_file_line_function",
5 (PyCFunction) c_file_line_function,
6 METH_NOARGS,
7 "Return the file, line and function name from the current C code."
8 },
9 /* ... */
10 {NULL, NULL, 0, NULL} /* Sentinel */
11};
And can be used thus (test code is in tests/unit/test_c_logging.py):
def test_c_file_line_function_file():
file, line, function = cLogging.c_file_line_function()
assert file == 'src/cpy/Logging/cLogging.c'
assert line == 148
assert function == 'c_file_line_function'