logger.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "logger.hpp"
  2. Logger::Logger(const std::string& filename, bool output_format) : output_format(output_format)
  3. {
  4. if(!output_format) {
  5. log_file.open(filename, std::ios::app);
  6. if (!log_file.is_open())
  7. {
  8. std::cerr << "Failed to open log file." << std::endl;
  9. exit(-1);
  10. }
  11. }
  12. }
  13. Logger::~Logger()
  14. {
  15. if (log_file.is_open())
  16. {
  17. log_file.close();
  18. }
  19. }
  20. void
  21. Logger::logInfo(const std::string& message)
  22. {
  23. log("INFO", message);
  24. }
  25. void
  26. Logger::logError(const std::string& message)
  27. {
  28. log("ERROR", message);
  29. fprintf(stderr, "ERROR while running programm, check logs for Pico status");
  30. exit(-1);
  31. }
  32. void
  33. Logger::logTimebase(const std::string& message, uint32_t timebase)
  34. {
  35. const std::string new_message = message + std::to_string(timebase);
  36. log("INFO", new_message);
  37. }
  38. void
  39. Logger::log_output(const uint32_t& reval_open)
  40. {
  41. std::string pico_state = return_fun(reval_open);
  42. pico_state == "PICO_OK" ? logInfo(pico_state) : logError(pico_state);
  43. }
  44. void
  45. Logger::log(const std::string& level, const std::string& message)
  46. {
  47. time_t now = time(0);
  48. char* dt = ctime(&now);
  49. if(output_format == true) {
  50. printf( "%s [%s]: %s\n", dt,level.c_str(),message.c_str());
  51. } else {
  52. if (log_file.is_open()) {
  53. log_file << dt << "[" << level << "]: " << message << std::endl;
  54. }
  55. }
  56. }