fork download
  1. #include <cstdio>
  2. #include <cstdarg>
  3. #include <iostream>
  4.  
  5. class Logger
  6. {
  7. public:
  8. Logger(){}
  9. ~Logger(){}
  10.  
  11. void info(const char* messageFormat, ...)
  12. {
  13. va_list args;
  14. va_start(args, messageFormat);
  15. std::string infoFormat = this->format<512>("[INFO] %s", messageFormat).c_str();
  16. vlog(infoFormat.c_str(), args);
  17. va_end(args);
  18. }
  19.  
  20. void vlog(const char* format, va_list args)
  21. {
  22. std::string logMessage = vFormat<512>(format, args);
  23. std::cout<<logMessage<<std::endl;
  24. }
  25.  
  26. template <size_t BufferSize>
  27. std::string format(const char* format, ...)
  28. {
  29. va_list args;
  30. va_start(args, format);
  31. std::string message = vFormat<BufferSize>(format, args).c_str();
  32. va_end(args);
  33. return message;
  34. }
  35.  
  36. template <size_t BufferSize>
  37. std::string vFormat(const char* format, va_list args)
  38. {
  39. char buffer[BufferSize];
  40. vsprintf(buffer, format, args);
  41. return std::string(buffer);
  42. }
  43. };
  44.  
  45. int main()
  46. {
  47. Logger log;
  48. log.info("This is a test with no args!");
  49. log.info("This is a %s with args!", "test");
  50. int n = 3;
  51. double dVal = 22.0/7.0;
  52. log.info("This is a test with %d args (double: %f, string: '%s')", n, dVal, "testString");
  53. return 0;
  54. }
Success #stdin #stdout 0.01s 2812KB
stdin
Standard input is empty
stdout
[INFO] This is a test with no args!
[INFO] This is a test with args!
[INFO] This is a test with 3 args (double: 3.142857, string: 'testString')