I have a cplusplus shared library, with a c interface, that writes log entries in stdout. I'm using it in a python application using the ctypes
library. The python application uses logging
library to write log entries.
What I need to do is to capture the stdout entries of the shared library to write the log entries with the logging
module. In other words, I want to redirect the stdout entries of the c library to the logging
module, so I can use logging
to write to files and console using its handlers.
I found that is possible to capture the stdout (see this SO question), but I can access it only when the c module call ends, and hence it is useless for logging. I want a none-blocking way to access the stdout entries.
A minimum example is as follows.
module.cpp (compiled with g++ -fPIC -shared module.cpp -o module.so
)
#include <unistd.h>
#include <iostream>
using namespace std;
extern "C" int callme()
{
cout<<"Hello world\n";
sleep(2);
cout<<"Some words\n";
sleep(2);
cout<<"Goodby world\n";
return 0;
}
The python app that calls it:
import ctypes as ct
import logging
format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG
logging.basicConfig(format=format)
logging.debug('This logging modules works like a charm!')
mymodule = ct.CDLL('./module.so')
mymodule.callme()
logging.info('I want to capture the shared library log entries')
logging.warning('Can I?')
This produces:
2016-02-04 16:16:35,976 - DEBUG - This logging modules works like a charm!
Hello world
Some words
Goodby world
2016-02-04 16:16:39,979 - INFO - I want to capture the shared library log entries
2016-02-04 16:16:39,979 - WARNING - Can I?
I have access to the c++ library, so a solution that needs modifications in the library are also welcome.