log.cpp 1.7 KB

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