C ++ concatenates various types into a string for a function

I have different parts of my application calling a log function to log data.

Class logger

std::string filename = "blahblah"; // variable to store the location of the properties file 
log4cpp::PropertyConfigurator::configure(filename);

void Logger::logging(const std::string& msg)
{
   Log4cpp::Category& myLogger = log4cpp::Category::getRoot();

   myLogger.log(log4cpp::Priority::INFO, msg);//only takes in string as input
}

Call class

Logger logMe;

int a = 5;
double b = 6;

logMe.logging("log this msg" + a + "," + b);

I realized that the above will give me an error, because athey bhave different types. One way to solve it is to usestd::to_string

logMe.logging("log this msg" + std::to_string(a) + "," + std::to_string(b));

However, I have hundreds of calls to the logging function, and it will take a lot of time to edit each call std::to_string. Is there / is there an easier way to do this?

Oh and to clarify, the code works earlier, since the previous method was to define the #define function.

#Define logging(FLAG, X)\
do {\
    ...
    clog << x; \
}while(0)

logging(LogFlag::Warning, "log this msg" << a << "," << b << endl);

But now I rewrite parts of the code to fit static testing.

Thanks in advance.

+4
3

logging, , std::stringstream

++ 17 fold,

template <typename Args ...>
void Logger::logging(Args ... args)
{
   std::stringstream ss;
   (ss << ... << args); 

   Log4cpp::Category& myLogger = log4cpp::Category::getRoot();

   myLogger.log(log4cpp::Priority::INFO, ss.str());
}

++ 11 14

template <typename ... Args >
void Logger::logging(Args ... args)
{
   std::stringstream ss;
   std::initializer_list<int> unused{ (ss << args, 0)... };

   Log4cpp::Category& myLogger = log4cpp::Category::getRoot();

   myLogger.log(log4cpp::Priority::INFO, ss.str());
}

, ,

logMe.logging("log this msg", a, ",", b);
+4

operator<<()

class Logger
{
     public:

          Logger &operator<<(const std::string &s)
          {
              logging(s)
              return *this;
          };

          Logger &operator<<(const char *s)
          {
              return operator<<(std::string(s));
          }


          template <class T>
               Logger &operator<<(const T &v)
          {
               std::ostringstream s;
               s << v;
               return operator<<(logging(ss.str()));
          };

       // other stuff you have in your class, including the logging() function
};

//  to use

logMe << "log this msg" << a << b;

, , .

+4

Pretty easy to use stringstream. Then you can convert it to std::stringwith str().

#include <sstream>
...
int a = 5;
double b = 6;

std::stringstream ss;
ss << "log this msg" << a << b;
std::cout << ss.str() << std::endl;
logMe.logging(ss.str());
+3
source

Source: https://habr.com/ru/post/1683501/


All Articles