c++ - Converting printf-style logger with stack buffer to stringstream -


i have logging solution defines macro this:

#define my_log(level, component, message, ...) { mylog::instance()->log(level, component, message, __file__, __line__, ##__va_args__); } 

the const char* message parameter using printf format, "my name %s , %u."

the actual logging method using declaring char buffer[2048] variable on stack , using vsnprintf convert va_list param, defined in message parameter, buffer. however, handling values can quite bigger 2k, buffer truncated thought reworking whole thing around stringstream more flexible.

when implementing solution, encountered problem retrieving va_args parameters list use << operator... solution available parse whole message parameter % values , retrieve them using va_arg type retrieved? need push text between % values, vsnprintf handy, need split strings on % push previous text stringstream... hint or idea me out issue?

i can't use external libs , support platforms , compilers may or may not support c++11, can't entirely rely on new language features, adding define support both implementation feasible. also, tons of traces in current codebase, can't change message format.

thanks!

i advice not try reimplementing vsnprintf on top of stringstream. if intend keep logger front-end unchanged, should keep vsnprintf!

first, should rather guess final size of formatted string , allocate buffer (using c++11 unique_ptr if it). should not fear allocation overhead stringstring under hood.

then, call vsnprintf buffer , test returned value. value (if positive) give minimum size required format output string correctly not including terminating null character. knowing can choose reallocate buffer correct size , call again vsnprintf it.

finally whatever have formatted string : - construct std::string - write somewhere (to file?) - don't forget release memory (or use unique_ptr).

note: don't use std::string buffer directly. writing buffer returned std::string::c_str() undefined behavior.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -