logthread.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "logthread.h"
  2. #include <QDebug>
  3. LogThread::LogThread(QObject *parent) : QThread(parent)
  4. {
  5. QDir dir("log");
  6. if(!dir.exists())
  7. dir.mkdir("log");
  8. logList.clear();
  9. }
  10. LogThread::~LogThread()
  11. {
  12. if(keepWorking)
  13. stop();
  14. this->deleteLater();
  15. }
  16. void LogThread::appendLog(QString log)
  17. {
  18. logList.append(log);
  19. }
  20. void LogThread::stop()
  21. {
  22. keepWorking = false;
  23. }
  24. void LogThread::run()
  25. {
  26. keepWorking = true;
  27. int day = -1;
  28. while (keepWorking) {
  29. if(logList.length()>0){
  30. QDate today = QDate::currentDate();
  31. if(day!=today.day()){
  32. uint t = QDateTime::currentDateTime().toTime_t();
  33. QDir dir("log");
  34. QFileInfoList list = dir.entryInfoList();
  35. for(int i=0;i<list.count();i++){
  36. if((QString::compare(list.at(i).fileName(),".")!=0)&&(QString::compare(list.at(i).fileName(),"..")!=0)){
  37. qDebug()<<list.at(i).fileName();
  38. if((t-list.at(i).lastModified().toTime_t())>(7*86400)){
  39. QFile::remove("log/"+list.at(i).fileName());
  40. }
  41. }
  42. }
  43. day = today.day();
  44. }
  45. QFile file(QString("log/log-%1%2%3.txt").arg(today.year(),4,10,QChar('0')).arg(today.month(),2,10,QChar('0')).arg(today.day(),2,10,QChar('0')));
  46. if(file.open(QIODevice::Text|QIODevice::Append|QIODevice::WriteOnly)){
  47. while (logList.length()>0) {
  48. file.write(logList.first().toUtf8()+"\n");
  49. logList.removeFirst();
  50. usleep(10000);
  51. }
  52. file.close();
  53. }
  54. }
  55. usleep(100000);
  56. }
  57. }