I have a cplusplus shared library with a c interface that writes log entries to stdout. I use it in a python application using a library ctypes. The python application uses a library loggingto write log entries.
What I need to do is grab the stdout entries in the shared library for writing log entries using the module logging. In other words, I want to redirect the stdout entries of the c library to the module logging, so I can use it loggingto write to files and the console using my handlers.
I found that it is possible to write stdout ( see this SO question ), but I can only access it after the c module call is completed, and therefore it is useless to register. I want no one to block access to stdout elements.
The 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 application 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 gives:
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 to the library is also welcome.
source
share