Note that there are some explanatory texts on larger screens.

plurals
  1. POVariable length arguments in log4cxx LOG4CXX_ macros
    primarykey
    data
    text
    <p>I am using log4cxx in a big C++ project but I really don't like how log4cxx handles multiple variables when logging:</p> <p>LOG4CXX_DEBUG(logger, "test " &lt;&lt; var1 &lt;&lt; " and " &lt;&lt; var3 " and .....)</p> <p>I prefer using printf like variable length arguments:</p> <p>LOG4CXX_DEBUG(logger, "test %d and %d", var1, var3)</p> <p>So I implemented this small wrapper on top of log4cxx</p> <pre><code>#include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;stdarg.h&gt; #include &lt;log4cxx/logger.h&gt; #include "log4cxx/basicconfigurator.h" const char * log_format(const char *fmt, ...); #define MYLOG_TRACE(logger, fmt, ...) LOG4CXX_TRACE(logger, log_format(fmt, ## __VA_ARGS__)) #define MYLOG_DEBUG(logger, fmt, ...) LOG4CXX_DEBUG(logger, log_format(fmt, ## __VA_ARGS__)) #define MYLOG_INFO(logger, fmt, ...) LOG4CXX_INFO(logger, log_format(fmt, ## __VA_ARGS__)) #define MYLOG_WARN(logger, fmt, ...) LOG4CXX_WARN(logger, log_format(fmt, ## __VA_ARGS__)) #define MYLOG_ERROR(logger, fmt, ...) LOG4CXX_ERROR(logger, log_format(fmt, ## __VA_ARGS__)) #define MYLOG_FATAL(logger, fmt, ...) LOG4CXX_FATAL(logger, log_format(fmt, ## __VA_ARGS__)) static log4cxx::LoggerPtr logger(log4cxx::Logger::getRootLogger()); int main(int argc, char **argv) { log4cxx::BasicConfigurator::configure(); MYLOG_INFO(logger, "Start "); MYLOG_WARN(logger, "In running this in %d threads safe?", 1000); MYLOG_INFO(logger, "End "); return 0; } const char *log_format(const char *fmt, ...) { va_list va; static char formatted[1024]; va_start(va, fmt); vsnprintf(formatted, 1024, fmt, va); va_end(va); return formatted; } </code></pre> <p>And this works perfectly but I know using that static variable (formatted) can become problematic if I start using threads and each thread logging to the same place.</p> <p>I am no expert in log4cxx so I was wondering if the LOG4CXX macros are handling concurrent thread access automatically? or do I have to implement some sort of locking around the log_format method? something that I wan't to avoid due to performance implications.</p> <p>To compile and test this program (in Ubuntu) use :</p> <pre><code>g++ -o loggertest loggertest.cpp -llog4cxx </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload