log.hpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #ifndef _FY_LOG_HPP_
  2. #define _FY_LOG_HPP_
  3. #include <unistd.h>
  4. #include <sys/syscall.h>
  5. #include "thread.hpp"
  6. namespace fy {
  7. class logcat {
  8. public:
  9. logcat(const std::string& file) {
  10. file_ = NULL;
  11. run_ = true;
  12. file_ = fopen(file.c_str(), "ab");
  13. if (file_ == NULL) {
  14. LOGD("failed to open %s", file.c_str());
  15. return;
  16. }
  17. fy::thread t(fy::logcat::logcat_thread, this);
  18. t.detach();
  19. }
  20. ~logcat() {
  21. run_ = false;
  22. LOGD("sup logcat stoped");
  23. if (file_) {
  24. fclose(file_);
  25. }
  26. }
  27. public:
  28. static void logcat_thread(void *arg) {
  29. logcat* log = (logcat*)arg;
  30. FILE * p = popen("logcat -v time", "r");
  31. if (p) {
  32. while (!feof(p) && log->run_) {
  33. char buffer[1024] = { 0 };
  34. char* line = fgets(buffer, sizeof(buffer), p);
  35. if (feof(p) || ferror(p)) {
  36. break;
  37. }
  38. if (line) {
  39. fputs(line, log->file_);
  40. fflush(log->file_);
  41. }
  42. static int lines = 0;
  43. ++lines;
  44. // if (lines % 5 == 0) {
  45. sync();
  46. // }
  47. }
  48. fclose(p);
  49. } else {
  50. LOGD("open failed %d", errno);
  51. }
  52. }
  53. private:
  54. FILE* file_;
  55. bool run_;
  56. };
  57. } /* namespace fy */
  58. #endif /* _FY_LOG_HPP_ */