diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 00172ee..0000000 --- a/LICENSE +++ /dev/null @@ -1,121 +0,0 @@ - 木兰宽松许可证, 第1版 - - 木兰宽松许可证, 第1版 - 2019年8月 http://license.coscl.org.cn/MulanPSL - - 您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第1版(“本许可证”)的如下条款的约束: - - 0. 定义 - - “软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。 - - “贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。 - - “法人实体”是指提交贡献的机构及其“关联实体”。 - - “关联实体”是指,对“本许可证”下的一方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。 - - “贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。 - - 1. 授予版权许可 - - 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。 - - 2. 授予专利许可 - - 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括仅因您或他人修改“贡献”或其他结合而将必然会侵犯到的专利权利要求。如您或您的“关联实体”直接或间接地(包括通过代理、专利被许可人或受让人),就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。 - - 3. 无商标许可 - - “本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。 - - 4. 分发限制 - - 您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。 - - 5. 免责声明与责任限制 - - “软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。 - - 条款结束。 - - 如何将木兰宽松许可证,第1版,应用到您的软件 - - 如果您希望将木兰宽松许可证,第1版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步: - - 1, 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字; - - 2, 请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中; - - 3, 请将如下声明文本放入每个源文件的头部注释中。 - - Copyright (c) [2019] [name of copyright holder] - [Software Name] is licensed under the Mulan PSL v1. - You can use this software according to the terms and conditions of the Mulan PSL v1. - You may obtain a copy of Mulan PSL v1 at: - http://license.coscl.org.cn/MulanPSL - THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR - PURPOSE. - See the Mulan PSL v1 for more details. - - - Mulan Permissive Software License,Version 1 - - Mulan Permissive Software License,Version 1 (Mulan PSL v1) - August 2019 http://license.coscl.org.cn/MulanPSL - - Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v1 (this License) with following terms and conditions: - - 0. Definition - - Software means the program and related documents which are comprised of those Contribution and licensed under this License. - - Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License. - - Legal Entity means the entity making a Contribution and all its Affiliates. - - Affiliates means entities that control, or are controlled by, or are under common control with a party to this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity. - - Contribution means the copyrightable work licensed by a particular Contributor under this License. - - 1. Grant of Copyright License - - Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not. - - 2. Grant of Patent License - - Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed, excluding of any patent claims solely be infringed by your or others’ modification or other combinations. If you or your Affiliates directly or indirectly (including through an agent, patent licensee or assignee), institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken. - - 3. No Trademark License - - No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in section 4. - - 4. Distribution Restriction - - You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software. - - 5. Disclaimer of Warranty and Limitation of Liability - - The Software and Contribution in it are provided without warranties of any kind, either express or implied. In no event shall any Contributor or copyright holder be liable to you for any damages, including, but not limited to any direct, or indirect, special or consequential damages arising from your use or inability to use the Software or the Contribution in it, no matter how it’s caused or based on which legal theory, even if advised of the possibility of such damages. - - End of the Terms and Conditions - - How to apply the Mulan Permissive Software License,Version 1 (Mulan PSL v1) to your software - - To apply the Mulan PSL v1 to your work, for easy identification by recipients, you are suggested to complete following three steps: - - i. Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner; - ii. Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package; - iii. Attach the statement to the appropriate annotated syntax at the beginning of each source file. - - Copyright (c) [2019] [name of copyright holder] - [Software Name] is licensed under the Mulan PSL v1. - You can use this software according to the terms and conditions of the Mulan PSL v1. - You may obtain a copy of Mulan PSL v1 at: - http://license.coscl.org.cn/MulanPSL - THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR - PURPOSE. - - See the Mulan PSL v1 for more details. \ No newline at end of file diff --git a/README.md b/README.md index e2b41bc..c1c2981 100644 --- a/README.md +++ b/README.md @@ -19,4 +19,6 @@ Qt编写的一些开源的demo,包括串口调试助手、网络调试助手 | 13 | ipaddress | IP地址输入控件 | | 14 | bgdemo | 无边框背景透明窗体 | | 15 | dbpage | 通用数据库翻页查询 | -| 16 | pngtool | PNG图片警告去除工具 | \ No newline at end of file +| 16 | pngtool | PNG图片警告去除工具 | +| 17 | savelog | 日志重定向输出类 | +| 18 | saveruntime | 运行时间记录类 | \ No newline at end of file diff --git a/savelog/frmsavelog.cpp b/savelog/frmsavelog.cpp new file mode 100644 index 0000000..7cfd2db --- /dev/null +++ b/savelog/frmsavelog.cpp @@ -0,0 +1,65 @@ +#pragma execution_character_set("utf-8") + +#include "frmsavelog.h" +#include "ui_frmsavelog.h" +#include "savelog.h" +#include "qdatetime.h" +#include "qtimer.h" +#include "qdebug.h" + +frmSaveLog::frmSaveLog(QWidget *parent) : QWidget(parent), ui(new Ui::frmSaveLog) +{ + ui->setupUi(this); + this->initForm(); +} + +frmSaveLog::~frmSaveLog() +{ + delete ui; +} + +void frmSaveLog::initForm() +{ + timer = new QTimer(this); + connect(timer, SIGNAL(timeout()), this, SLOT(append())); + timer->setInterval(1000); + + SaveLog::Instance()->setPath(qApp->applicationDirPath()); +} + +void frmSaveLog::append() +{ + QString msg = QString("当前时间: %1 测试打印输出消息").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")); + ui->txtMain->append(msg); + qDebug() << msg; +} + +void frmSaveLog::on_btnDebug_clicked() +{ + QString msg = QString("当前时间: %1 手动插入消息").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")); + ui->txtMain->append(msg); + qDebug() << msg; +} + +void frmSaveLog::on_ckTimer_stateChanged(int arg1) +{ + if (arg1 == 0) { + timer->stop(); + } else { + timer->start(); + } +} + +void frmSaveLog::on_ckNet_stateChanged(int arg1) +{ + SaveLog::Instance()->setToNet(arg1 != 0); +} + +void frmSaveLog::on_ckSave_stateChanged(int arg1) +{ + if (arg1 == 0) { + SaveLog::Instance()->stop(); + } else { + SaveLog::Instance()->start(); + } +} diff --git a/savelog/frmsavelog.h b/savelog/frmsavelog.h new file mode 100644 index 0000000..c967803 --- /dev/null +++ b/savelog/frmsavelog.h @@ -0,0 +1,32 @@ +#ifndef FRMSAVELOG_H +#define FRMSAVELOG_H + +#include + +namespace Ui { +class frmSaveLog; +} + +class frmSaveLog : public QWidget +{ + Q_OBJECT + +public: + explicit frmSaveLog(QWidget *parent = 0); + ~frmSaveLog(); + +private: + Ui::frmSaveLog *ui; + QTimer *timer; + +private slots: + void initForm(); + void append(); + void on_btnDebug_clicked(); + void on_ckTimer_stateChanged(int arg1); + void on_ckNet_stateChanged(int arg1); + void on_ckSave_stateChanged(int arg1); + +}; + +#endif // FRMSAVELOG_H diff --git a/savelog/frmsavelog.ui b/savelog/frmsavelog.ui new file mode 100644 index 0000000..d8e6ec9 --- /dev/null +++ b/savelog/frmsavelog.ui @@ -0,0 +1,58 @@ + + + frmSaveLog + + + + 0 + 0 + 400 + 300 + + + + Form + + + + + + 定时器打印消息 + + + + + + + 保存日志 + + + + + + + + 0 + 0 + + + + 手动插入消息 + + + + + + + + + + 重定向到网络 + + + + + + + + diff --git a/savelog/main.cpp b/savelog/main.cpp new file mode 100644 index 0000000..ada65d9 --- /dev/null +++ b/savelog/main.cpp @@ -0,0 +1,31 @@ +#pragma execution_character_set("utf-8") + +#include "frmsavelog.h" +#include +#include + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + a.setFont(QFont("Microsoft Yahei", 9)); + +#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0)) +#if _MSC_VER + QTextCodec *codec = QTextCodec::codecForName("gbk"); +#else + QTextCodec *codec = QTextCodec::codecForName("utf-8"); +#endif + QTextCodec::setCodecForLocale(codec); + QTextCodec::setCodecForCStrings(codec); + QTextCodec::setCodecForTr(codec); +#else + QTextCodec *codec = QTextCodec::codecForName("utf-8"); + QTextCodec::setCodecForLocale(codec); +#endif + + frmSaveLog w; + w.setWindowTitle("输出日志文件"); + w.show(); + + return a.exec(); +} diff --git a/savelog/savelog.cpp b/savelog/savelog.cpp new file mode 100644 index 0000000..00f0bcf --- /dev/null +++ b/savelog/savelog.cpp @@ -0,0 +1,193 @@ +#include "savelog.h" +#include "qmutex.h" +#include "qfile.h" +#include "qtcpsocket.h" +#include "qtcpserver.h" +#include "qdatetime.h" +#include "qapplication.h" +#include "qtimer.h" +#include "qstringlist.h" + +#define QDATE qPrintable(QDate::currentDate().toString("yyyy-MM-dd")) + +//日志重定向 +#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0)) +void Log(QtMsgType type, const char *msg) +#else +void Log(QtMsgType type, const QMessageLogContext &, const QString &msg) +#endif +{ + //加锁,防止多线程中qdebug太频繁导致崩溃 + QMutex mutex; + QMutexLocker locker(&mutex); + QString content; + + //这里可以根据不同的类型加上不同的头部用于区分 + switch (type) { + case QtDebugMsg: + content = QString("%1").arg(msg); + break; + + case QtWarningMsg: + content = QString("%1").arg(msg); + break; + + case QtCriticalMsg: + content = QString("%1").arg(msg); + break; + + case QtFatalMsg: + content = QString("%1").arg(msg); + break; + } + + SaveLog::Instance()->save(content); +} + +QScopedPointer SaveLog::self; +SaveLog *SaveLog::Instance() +{ + if (self.isNull()) { + static QMutex mutex; + QMutexLocker locker(&mutex); + if (self.isNull()) { + self.reset(new SaveLog); + } + } + + return self.data(); +} + +SaveLog::SaveLog(QObject *parent) : QObject(parent) +{ + //必须用信号槽形式,不然提示 QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread + //估计日志钩子可能单独开了线程 + connect(this, SIGNAL(send(QString)), SendLog::Instance(), SLOT(send(QString))); + + file = new QFile(this); + toNet = false; + //默认取应用程序根目录 + path = qApp->applicationDirPath(); + //默认取应用程序可执行文件名称 + QString str = qApp->applicationFilePath(); + QStringList list = str.split("/"); + name = list.at(list.count() - 1).split(".").at(0); + fileName = ""; +} + +SaveLog::~SaveLog() +{ + file->close(); +} + +//安装日志钩子,输出调试信息到文件,便于调试 +void SaveLog::start() +{ +#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0)) + qInstallMsgHandler(Log); +#else + qInstallMessageHandler(Log); +#endif +} + +//卸载日志钩子 +void SaveLog::stop() +{ +#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0)) + qInstallMsgHandler(0); +#else + qInstallMessageHandler(0); +#endif +} + +void SaveLog::save(const QString &content) +{ + //如果重定向输出到网络则通过网络发出去,否则输出到日志文件 + if (toNet) { + emit send(content); + } else { + //方法改进:之前每次输出日志都打开文件,改成只有当日期改变时才新建和打开文件 + QString fileName = QString("%1/%2_log_%3.txt").arg(path).arg(name).arg(QDATE); + if (this->fileName != fileName) { + this->fileName = fileName; + if (file->isOpen()) { + file->close(); + } + + file->setFileName(fileName); + file->open(QIODevice::WriteOnly | QIODevice::Append | QFile::Text); + } + + QTextStream logStream(file); + logStream << content << "\n"; + } +} + +void SaveLog::setToNet(bool toNet) +{ + this->toNet = toNet; +} + +void SaveLog::setPath(const QString &path) +{ + this->path = path; +} + +void SaveLog::setName(const QString &name) +{ + this->name = name; +} + + +//网络发送日志数据类 +QScopedPointer SendLog::self; +SendLog *SendLog::Instance() +{ + if (self.isNull()) { + static QMutex mutex; + QMutexLocker locker(&mutex); + if (self.isNull()) { + self.reset(new SendLog); + } + } + + return self.data(); +} + +SendLog::SendLog(QObject *parent) +{ + socket = NULL; + server = new QTcpServer(this); + connect(server, SIGNAL(newConnection()), this, SLOT(newConnection())); + + int listenPort = 6000; +#if (QT_VERSION > QT_VERSION_CHECK(5,0,0)) + server->listen(QHostAddress::AnyIPv4, listenPort); +#else + server->listen(QHostAddress::Any, listenPort); +#endif +} + +SendLog::~SendLog() +{ + if (socket != NULL) { + socket->disconnectFromHost(); + } + + server->close(); +} + +void SendLog::newConnection() +{ + while (server->hasPendingConnections()) { + socket = server->nextPendingConnection(); + } +} + +void SendLog::send(const QString &content) +{ + if (socket != NULL && socket->isOpen()) { + socket->write(content.toUtf8()); + socket->flush(); + } +} diff --git a/savelog/savelog.h b/savelog/savelog.h new file mode 100644 index 0000000..1b91931 --- /dev/null +++ b/savelog/savelog.h @@ -0,0 +1,84 @@ +#ifndef SAVELOG_H +#define SAVELOG_H + +#include + +class QFile; +class QTcpSocket; +class QTcpServer; + +#ifdef quc +#if (QT_VERSION < QT_VERSION_CHECK(5,7,0)) +#include +#else +#include +#endif + +class QDESIGNER_WIDGET_EXPORT SaveLog : public QObject +#else +class SaveLog : public QObject +#endif + +{ + Q_OBJECT +public: + static SaveLog *Instance(); + explicit SaveLog(QObject *parent = 0); + ~SaveLog(); + +private: + static QScopedPointer self; + + //文件对象 + QFile *file; + //是否重定向到网络 + bool toNet; + //日志文件路径 + QString path; + //日志文件名称 + QString name; + //日志文件完整名称 + QString fileName; + +signals: + void send(const QString &content); + +public slots: + //启动日志服务 + void start(); + //暂停日志服务 + void stop(); + //保存日志 + void save(const QString &content); + + //设置是否重定向到网络 + void setToNet(bool toNet); + //设置日志文件存放路径 + void setPath(const QString &path); + //设置日志文件名称 + void setName(const QString &name); + +}; + +class SendLog : public QObject +{ + Q_OBJECT +public: + static SendLog *Instance(); + explicit SendLog(QObject *parent = 0); + ~SendLog(); + +private: + static QScopedPointer self; + QTcpSocket *socket; + QTcpServer *server; + +private slots: + void newConnection(); + +public slots: + //发送日志 + void send(const QString &content); +}; + +#endif // SAVELOG_H diff --git a/savelog/savelog.pro b/savelog/savelog.pro new file mode 100644 index 0000000..9b3db26 --- /dev/null +++ b/savelog/savelog.pro @@ -0,0 +1,23 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2019-02-16T15:08:47 +# +#------------------------------------------------- + +QT += core gui network + +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets + +TARGET = savelog +TEMPLATE = app +DESTDIR = $$PWD/../bin +CONFIG += warn_off + +SOURCES += main.cpp +SOURCES += frmsavelog.cpp +SOURCES += savelog.cpp + +HEADERS += frmsavelog.h +HEADERS += savelog.h + +FORMS += frmsavelog.ui diff --git a/saveruntime/frmsaveruntime.cpp b/saveruntime/frmsaveruntime.cpp new file mode 100644 index 0000000..39e7469 --- /dev/null +++ b/saveruntime/frmsaveruntime.cpp @@ -0,0 +1,24 @@ +#pragma execution_character_set("utf-8") + +#include "frmsaveruntime.h" +#include "ui_frmsaveruntime.h" +#include "saveruntime.h" + +frmSaveRunTime::frmSaveRunTime(QWidget *parent) : QWidget(parent), ui(new Ui::frmSaveRunTime) +{ + ui->setupUi(this); +} + +frmSaveRunTime::~frmSaveRunTime() +{ + delete ui; +} + +void frmSaveRunTime::on_checkBox_stateChanged(int arg1) +{ + if (arg1 == 0) { + SaveRunTime::Instance()->stop(); + } else { + SaveRunTime::Instance()->start(); + } +} diff --git a/saveruntime/frmsaveruntime.h b/saveruntime/frmsaveruntime.h new file mode 100644 index 0000000..88412aa --- /dev/null +++ b/saveruntime/frmsaveruntime.h @@ -0,0 +1,25 @@ +#ifndef FRMSAVERUNTIME_H +#define FRMSAVERUNTIME_H + +#include + +namespace Ui { +class frmSaveRunTime; +} + +class frmSaveRunTime : public QWidget +{ + Q_OBJECT + +public: + explicit frmSaveRunTime(QWidget *parent = 0); + ~frmSaveRunTime(); + +private: + Ui::frmSaveRunTime *ui; + +private slots: + void on_checkBox_stateChanged(int arg1); +}; + +#endif // FRMSAVERUNTIME_H diff --git a/saveruntime/frmsaveruntime.ui b/saveruntime/frmsaveruntime.ui new file mode 100644 index 0000000..30e999b --- /dev/null +++ b/saveruntime/frmsaveruntime.ui @@ -0,0 +1,41 @@ + + + frmSaveRunTime + + + + 0 + 0 + 400 + 300 + + + + Form + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + 启动服务 + + + + + + + + diff --git a/saveruntime/main.cpp b/saveruntime/main.cpp new file mode 100644 index 0000000..48dd92a --- /dev/null +++ b/saveruntime/main.cpp @@ -0,0 +1,31 @@ +#pragma execution_character_set("utf-8") + +#include "frmsaveruntime.h" +#include +#include + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + a.setFont(QFont("Microsoft Yahei", 9)); + +#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0)) +#if _MSC_VER + QTextCodec *codec = QTextCodec::codecForName("gbk"); +#else + QTextCodec *codec = QTextCodec::codecForName("utf-8"); +#endif + QTextCodec::setCodecForLocale(codec); + QTextCodec::setCodecForCStrings(codec); + QTextCodec::setCodecForTr(codec); +#else + QTextCodec *codec = QTextCodec::codecForName("utf-8"); + QTextCodec::setCodecForLocale(codec); +#endif + + frmSaveRunTime w; + w.setWindowTitle("保存运行时间"); + w.show(); + + return a.exec(); +} diff --git a/saveruntime/saveruntime.cpp b/saveruntime/saveruntime.cpp new file mode 100644 index 0000000..d8ef753 --- /dev/null +++ b/saveruntime/saveruntime.cpp @@ -0,0 +1,221 @@ +#include "saveruntime.h" +#include "qmutex.h" +#include "qapplication.h" +#include "qtimer.h" +#include "qfile.h" +#include "qtextstream.h" +#include "qstringlist.h" +#include "qdebug.h" + +#ifdef Q_OS_WIN +#define NEWLINE "\r\n" +#else +#define NEWLINE "\n" +#endif + +QScopedPointer SaveRunTime::self; +SaveRunTime *SaveRunTime::Instance() +{ + if (self.isNull()) { + static QMutex mutex; + QMutexLocker locker(&mutex); + if (self.isNull()) { + self.reset(new SaveRunTime); + } + } + + return self.data(); +} + +SaveRunTime::SaveRunTime(QObject *parent) : QObject(parent) +{ + path = qApp->applicationDirPath(); + QString str = qApp->applicationFilePath(); + QStringList list = str.split("/"); + name = list.at(list.count() - 1).split(".").at(0); + + saveInterval = 1 * 60 * 1000; + startTime = QDateTime::currentDateTime(); + + timerSave = new QTimer(this); + timerSave->setInterval(saveInterval); + connect(timerSave, SIGNAL(timeout()), this, SLOT(saveLog())); +} + +void SaveRunTime::start() +{ + timerSave->start(); + + initLog(); + appendLog(); + saveLog(); +} + +void SaveRunTime::stop() +{ + timerSave->stop(); +} + +void SaveRunTime::getDiffValue(const QDateTime &startTime, const QDateTime &endTime, int &day, int &hour, int &minute) +{ + qint64 sec = startTime.secsTo(endTime); + day = hour = minute = 0; + int seconds = 0; + + while (sec > 0) { + seconds++; + if (seconds == 60) { + minute++; + seconds = 0; + } + + if (minute == 60) { + hour++; + minute = 0; + } + + if (hour == 24) { + day++; + hour = 0; + } + + sec--; + } +} + +void SaveRunTime::initLog() +{ + //判断当前年份的记事本文件是否存在,不存在则新建并且写入标题 + //存在则自动读取最后一行的id号 记事本文件格式内容 + //幢号 开始时间 结束时间 已运行时间 + //1 2016-01-01 12:33:33 2016-02-05 12:12:12 day: 0 hour: 0 minute: 0 + + logFile = QString("%1/%2_runtime_%3.txt").arg(path).arg(name).arg(QDate::currentDate().year()); + QFile file(logFile); + + if (file.size() == 0) { + if (file.open(QFile::WriteOnly | QFile::Text)) { + QString strID = QString("%1\t").arg("编号"); + QString strStartTime = QString("%1\t\t").arg("开始时间"); + QString strEndTime = QString("%1\t\t").arg("结束时间"); + QString strRunTime = QString("%1").arg("已运行时间"); + QString line = strID + strStartTime + strEndTime + strRunTime; + + QTextStream stream(&file); + stream << line << NEWLINE; + file.close(); + + lastID = 0; + } + } else { + if (file.open(QFile::ReadOnly)) { + QString lastLine; + + while (!file.atEnd()) { + lastLine = file.readLine(); + } + + file.close(); + + QStringList list = lastLine.split("\t"); + lastID = list.at(0).toInt(); + } + } + + lastID++; +} + +void SaveRunTime::appendLog() +{ + logFile = QString("%1/%2_runtime_%3.txt").arg(path).arg(name).arg(QDate::currentDate().year()); + QFile file(logFile); + + //写入当前首次运行时间 + if (file.open(QFile::WriteOnly | QFile::Append | QFile::Text)) { + QString strID = QString("%1\t").arg(lastID); + QString strStartTime = QString("%1\t").arg(startTime.toString("yyyy-MM-dd HH:mm:ss")); + QString strEndTime = QString("%1\t").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")); + + int day, hour, minute; + getDiffValue(startTime, QDateTime::currentDateTime(), day, hour, minute); + QString strRunTime = QString("%1 天 %2 时 %3 分").arg(day).arg(hour).arg(minute); + QString line = strID + strStartTime + strEndTime + strRunTime; + + QTextStream stream(&file); + stream << line << NEWLINE; + file.close(); + } +} + +void SaveRunTime::saveLog() +{ + //每次保存都是将之前的所有文本读取出来,然后替换最后一行即可 + logFile = QString("%1/%2_runtime_%3.txt").arg(path).arg(name).arg(QDate::currentDate().year()); + QFile file(logFile); + + //如果日志文件不存在,则初始化一个日志文件 + if (file.size() == 0) { + initLog(); + appendLog(); + return; + } + + if (file.open(QFile::ReadWrite)) { + //一行行读取到链表 + QStringList content; + while (!file.atEnd()) { + content.append(file.readLine()); + } + + //重新清空文件 + file.resize(0); + + //如果行数小于2则返回 + if (content.count() < 2) { + file.close(); + return; + } + + QString lastLine = content.last(); + QStringList list = lastLine.split("\t"); + + //计算已运行时间 + int day, hour, minute; + getDiffValue(startTime, QDateTime::currentDateTime(), day, hour, minute); + QString strRunTime = QString("%1 天 %2 时 %3 分").arg(day).arg(hour).arg(minute); + + //重新拼接最后一行 + list[2] = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"); + list[3] = strRunTime; + lastLine = list.join("\t"); + + //重新替换最后一行并写入新的数据 + content[content.count() - 1] = lastLine; + + QTextStream stream(&file); + stream << content.join("") << NEWLINE; + file.close(); + } +} + +void SaveRunTime::setPath(const QString &path) +{ + if (this->path != path) { + this->path = path; + } +} + +void SaveRunTime::setName(const QString &name) +{ + if (this->name != name) { + this->name = name; + } +} + +void SaveRunTime::setSaveInterval(int saveInterval) +{ + if (this->saveInterval != saveInterval) { + this->saveInterval = saveInterval; + timerSave->setInterval(saveInterval); + } +} diff --git a/saveruntime/saveruntime.h b/saveruntime/saveruntime.h new file mode 100644 index 0000000..060539d --- /dev/null +++ b/saveruntime/saveruntime.h @@ -0,0 +1,54 @@ +#ifndef SAVERUNTIME_H +#define SAVERUNTIME_H + +#include +#include +class QTimer; + +#ifdef quc +#if (QT_VERSION < QT_VERSION_CHECK(5,7,0)) +#include +#else +#include +#endif + +class QDESIGNER_WIDGET_EXPORT SaveRunTime : public QObject +#else +class SaveRunTime : public QObject +#endif + +{ + Q_OBJECT +public: + static SaveRunTime *Instance(); + explicit SaveRunTime(QObject *parent = 0); + +private: + static QScopedPointer self; + QString path; //日志文件路径 + QString name; //日志文件名称 + + int lastID; + int saveInterval; + QDateTime startTime; + QString logFile; + QTimer *timerSave; + +private: + void getDiffValue(const QDateTime &startTime, const QDateTime &endTime, int &day, int &hour, int &minute); + +signals: + +public slots: + void start(); //启动服务 + void stop(); //停止服务 + void initLog(); //初始化日志文件 + void appendLog(); //追加一条记录到日志文件 + void saveLog(); //保存运行时间到日志文件 + + void setPath(const QString &path); + void setName(const QString &name); + void setSaveInterval(int saveInterval); +}; + +#endif // SAVERUNTIME_H diff --git a/saveruntime/saveruntime.pro b/saveruntime/saveruntime.pro new file mode 100644 index 0000000..430ea87 --- /dev/null +++ b/saveruntime/saveruntime.pro @@ -0,0 +1,23 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2019-02-16T15:08:47 +# +#------------------------------------------------- + +QT += core gui + +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets + +TARGET = saveruntime +TEMPLATE = app +DESTDIR = $$PWD/../bin +CONFIG += warn_off + +SOURCES += main.cpp +SOURCES += frmsaveruntime.cpp +SOURCES += saveruntime.cpp + +HEADERS += frmsaveruntime.h +HEADERS += saveruntime.h + +FORMS += frmsaveruntime.ui