log.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include "log.h"
  2. #include <fstream>
  3. #include <chrono>
  4. #include <iomanip>
  5. #include <sstream>
  6. void pika::LogManager::init(std::string name)
  7. {
  8. this->name = name;
  9. firstLog = 0;
  10. }
  11. void pika::LogManager::log(const char *l, int type)
  12. {
  13. #ifdef PIKA_DEVELOPMENT
  14. logInternally(l, type);
  15. logToFile(l, type);
  16. logToPushNotification(l, type);
  17. #endif
  18. #ifdef PIKA_PRODUCTION
  19. #if !PIKA_REMOVE_LOGS_TO_FILE_IN_PRODUCTION
  20. logToFile(l, type);
  21. #endif
  22. #if !PIKA_REMOVE_LOGS_TO_NOTIFICATIONS_IN_PRODUCTION
  23. logToPushNotification(l, type);
  24. #endif
  25. #endif
  26. }
  27. std::stringstream formatLog(const char *l, int type)
  28. {
  29. auto time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  30. std::stringstream s;
  31. s << "#" << std::put_time(std::localtime(&time), "%Y-%m-%d %X");
  32. if (type == pika::logWarning)
  33. {
  34. s << "[warning]";
  35. }
  36. else if (type == pika::logError)
  37. {
  38. s << "[error]";
  39. }
  40. s << ": ";
  41. s << l << "\n";
  42. return s;
  43. }
  44. void pika::LogManager::logToFile(const char *l, int type)
  45. {
  46. if (name == "") { name = DefaultLogFile; }
  47. //todo unlickely atribute
  48. if (!firstLog)
  49. {
  50. firstLog = 1;
  51. std::ofstream file(name); //no need to check here
  52. file.close(); //clear the file content
  53. }
  54. pika::logToFile(name.c_str(), l, type);
  55. }
  56. void pika::LogManager::logInternally(const char *l, int type)
  57. {
  58. if (internalLogs.size() >= maxInternalLogCount)
  59. {
  60. internalLogs.pop_front();
  61. }
  62. internalLogs.push_back(formatLog(l, type).str());
  63. }
  64. void pika::LogManager::logToPushNotification(const char *l, int type)
  65. {
  66. if (pushNotificationManager)
  67. {
  68. pushNotificationManager->pushNotification(l, type);
  69. }
  70. }
  71. void pika::logToFile(const char *fileName, const char *l, int type)
  72. {
  73. std::ofstream file(fileName, std::ofstream::app);
  74. if (!file.is_open()) { return; }
  75. file << formatLog(l, type).rdbuf();
  76. file.close();
  77. }