Our C/C++ project is using a new internal script that liberally wraps every function in SWIG to make available to python scripts. It chokes on our logger function since SWIG cannot wrap variadic functions well.
So I decided to hide the variadic functionality in a macro that SWIG will never trip over, shown in a simplified example below:
#include <iostream>
void LogPrint(char *file, int line, char* msg)
{
std::cout << file << ":" << line;
std::cout << " [ " << msg << " ] ";
std::cout << std::endl;
}
#define MAX_LOG 256
#define LogPrintf(msg, args...) \
{ \
char *msg_buffer = new char[MAX_LOG]; \
snprintf(msg_buffer, MAX_LOG, msg, ##args); \
开发者_运维知识库 Log(__FILE__, __LINE__, msg_buffer); \
delete [] msg_buffer; \
}
main()
{
LogPrintf("%s = %f", "tau", 6.28318);
LogPrintf("%s = %f", "pi", 3.14159);
}
Is this okay? Are there better solutions to this problem? Thanks.
Python makes it trivial to assemble formatted strings within Python, so I would just offer the simple "give me a string and I log it" error.
For the general case, though, you might consider:
1) boost::format
2) emulating the iostream interface by creating a class that holds a std::stringstream
member, overloading operator<<
to forward to the stringstream's operator<<
, and then adding some other way to actually log the "buffer" contents (one approach is to log in the destructor of the object - making it non-copyable is probably a good idea - so you can do something like Logger() << "foo" << bar;
- the temporary object lifetime is extended to the end of the line, the operator overloads build up the buffer contents, and then the dtor runs and outputs the .str()
of the stringstream to whereever).
精彩评论