logthread.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "logthread.h"
  2. LogThread::LogThread(QObject *parent) :
  3. QThread(parent)
  4. {
  5. keep = false;
  6. dataList.clear();
  7. QDir path("/usky/data-agbox/agmqttprocess/log");
  8. if(!path.exists()){
  9. system("mkdir -p /usky/data-agbox/agmqttprocess/log/");
  10. }
  11. file = new QFile("/usky/data-agbox/agmqttprocess/log/mqttprocess-"+QDate::currentDate().toString("yyyyMMdd")+".log");
  12. day = QDate::currentDate().day();
  13. }
  14. void LogThread::appendData(QString data)
  15. {
  16. dataList.append(data);
  17. }
  18. void LogThread::stop()
  19. {
  20. keep = false;
  21. }
  22. void LogThread::run()
  23. {
  24. printf("log thread start\n");
  25. if(file->open(QIODevice::ReadWrite|QIODevice::Append|QIODevice::Text)){
  26. file->write(QString("agMqttProcess start at %1.\r\n").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")).toUtf8());
  27. file->close();
  28. }
  29. keep = true;
  30. while(keep){
  31. if(dataList.length()>0){
  32. if(day!=QDate::currentDate().day()){
  33. day = QDate::currentDate().day();
  34. file = new QFile("/usky/data-agbox/agmqttprocess/log/mqttprocess-"+QDate::currentDate().toString("yyyyMMdd")+".log");
  35. uint l_time = QDateTime::currentDateTime().toTime_t()-7*86400;
  36. QDir dir("/usky/data-agbox/agmqttprocess/log");
  37. QFileInfoList file_list = dir.entryInfoList(QDir::Files);
  38. for(int i=0;i<file_list.size();i++){
  39. QFileInfo f_info = file_list.at(i);
  40. if(f_info.lastModified().toTime_t()<l_time){
  41. QFile(f_info.canonicalFilePath()).remove();
  42. }
  43. }
  44. }
  45. if(file->open(QIODevice::ReadWrite|QIODevice::Append|QIODevice::Text)){
  46. while(dataList.length()>0){
  47. file->write(dataList.first().toUtf8());
  48. file->write("\r\n");
  49. dataList.removeFirst();
  50. usleep(1000);
  51. }
  52. file->close();
  53. }
  54. }
  55. usleep(50000);
  56. }
  57. }