各位大佬,如何让软件生成日志文件?

亭台六七座 2020-03-29 03:08:13
各位大佬,如何让软件生成日志文件?

需要写很多 qDebug()吗?
...全文
1075 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
void MvPublic::Createlog(QString  filepath, int nums)
{
logfilePath = filepath; //全局私有变量,日志路径-格式为 C:/MVLOG/ContraolBoard
QDir filedir(filepath);
if (filedir.exists()) //如果路径存在,删除老的老的日志文件
{
QFileInfoList filelist = filedir.entryInfoList(QDir::Files,QDir::Name); //过滤当前路径下的文件并排序
if(filelist.count()>nums)
{
QStringList logfilelist;
for(int i=0;i<filelist.count();i++)
{
if(QString::compare(filelist[i].suffix(),"log",Qt::CaseSensitive)==0) //判断是否为日志文件
{
logfilelist.append(filelist[i].path());
}
}
if(logfilelist.count()>nums) //判断数量是否大于指定保存数量
{
for(int i=0;i<logfilelist.count()-nums;i++)
filedir.remove(logfilelist[i]); //删除多余的日志文件
}
}
}
else
filedir.mkpath(filepath); //不存在就创建路径

logfileName = logfilePath+"/"+QString(QDateTime::currentDateTime().toString("yyyyMMdd"))+".log";
logfile.setFileName(logfileName);
logfile.open(QIODevice::WriteOnly|QIODevice::Append);
logStream.setDevice(&logfile);
Writlog("*****************应用程序启动*****************");
}


void MvPublic::Writlog(QString sloginfo)
{
logMutex.lock();
QString Currentfilename = logfilePath+"/"+QString(QDateTime::currentDateTime().toString("yyyyMMdd"))+".log";
if (Currentfilename!=logfileName) //新的一天,重新创建一个文件
{
logfile.close();
logfileName=Currentfilename;
logfile.setFileName(logfileName);
logfile.open(QIODevice::WriteOnly|QIODevice::Append);
}
sloginfo = "["+QString(QDateTime::currentDateTime().toString("hh:mm:ss:zzz"))+"] "+sloginfo;
logStream<<sloginfo<<"\r\n";
logStream.flush();
logfile.flush();
logMutex.unlock();
}
scribbler 2020-04-23
  • 打赏
  • 举报
回复
拦截消息

static void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg);
qInstallMessageHandler(messageOutput);
static void writeLogFile(const QString &msg);
static QString getLogFilePath();
static void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
static QMutex mutex;
mutex.lock();
QByteArray localMsg = msg.toUtf8();
switch (type)
{
case QtDebugMsg:
case QtInfoMsg:
case QtWarningMsg:
if( debug )
{
fprintf(stdout, "%s\n", QVariant(localMsg).toString().toUtf8().constData());
fflush(stdout);
}
break;
case QtCriticalMsg:
if( debug )
{
fprintf(stderr, "%s\n", QVariant(localMsg).toString().toUtf8().constData());
fflush(stderr);
}
break;
case QtFatalMsg:

fprintf(stderr, "%s\n", QVariant(localMsg).toString().toUtf8().constData());
fflush(stderr);
break;
// abort();
}
writeLogFile(text);
mutex.unlock();
}
static void writeLogFile(const QString &msg)
{
if(qApp==nullptr)
{
return;
}

QString path = getLogFilePath();
QLocale lo(QLocale::C);
QDateTime dateTime = QDateTime::currentDateTimeUtc();
dateTime = dateTime.toLocalTime();
QString name = lo.toString(dateTime, "yyyyMMdd.log");

QString filePath = path + name;

QFile file(filePath);
if(!file.exists ())
{
file.open(QIODevice::WriteOnly);
file.close();
}
if(file.open(QIODevice::WriteOnly | QIODevice::Append))
{
QTextStream stream(&file);
stream << msg << "\r\n";
file.flush();
file.close();
}
}
static QString getLogFilePath()
{
QString logPath = QString::fromStdString(Application::GetCurrentApplicationSupportDirectory());

logPath = logPath + QDir::separator() + "logs" + QDir::separator();

QDir dir(logPath);
if(!dir.exists(logPath))
{
dir.mkpath(logPath);
}
return logPath;
}
未狂 2020-04-21
  • 打赏
  • 举报
回复
qDebug可以增加一个控制,让qDebug实现日志功能

#include "widget.h"
#include <QApplication>
#include <iostream>
#include <cstdlib>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <QMutex>
#include <QDateTime>
using namespace std;

QMutex mutex;//日志代码互斥锁
QString timePoint;

//日志生成
void LogMsgOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
 {	 
	 mutex.lock();
	 cout << msg.toStdString() << endl;
	 //Critical Resource of Code
     QByteArray localMsg = msg.toLocal8Bit();
	 QString log;
	 
     switch (type) {
     case QtDebugMsg:
         //fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		 log.append(QString("Debug  File:%1 %2  Line:%3  Content:%4").arg(context.file).arg(context.function).arg(context.line).arg(msg));
         break;
     case QtInfoMsg:
         //fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		 log.append(QString("Info: %1  %2  %3  %4").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));
         break;
     case QtWarningMsg:
         //fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		 log.append(QString("Warning: %1  %2  %3  %4").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));
         break;
     case QtCriticalMsg:
         //fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		 log.append(QString("Critical: %1  %2  %3  %4").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));
         break;
     case QtFatalMsg:
         //fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		 log.append(QString("Fatal: %1  %2  %3  %4").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));
         abort();
     }
	 
	 QFile file;
	 QString path = QString("log%1.lgt").arg(timePoint);
	 file.setFileName(path);
	 if (!file.open(QIODevice::ReadWrite | QIODevice::Append))
	 {
		 QString erinfo = file.errorString();
		 cout << erinfo.toStdString() << endl;
		 return;
	 }
	 QTextStream out(&file);
	 out << "\n\r" << log;
	 file.close();

	 mutex.unlock();
 }

int main(int argc, char *argv[])
{
	//release模式下,调试信息输出至日志文件
#ifndef _DEBUG
	timePoint = QDateTime::currentDateTime().toString("yyyyMMddHHmmss");
	qInstallMessageHandler(LogMsgOutput);
#endif
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

smile_sambery 2020-04-12
  • 打赏
  • 举报
回复
class Log {
public:
enum logLevel {
debug,
info,
warning,
error
};
static log* getinstance(){
//写一个单例类
}
void saveLogToFile(logLevel level, QString logInfo){
//判断log等级
//上锁
//打开文件,并写入数据
//关闭文件
//解锁
}
private:
Log() {
//创建log文件
}
static log *logSingleInstance;
logLevel m_logLevel;
QString logPath;
};
smile_sambery 2020-04-12
  • 打赏
  • 举报
回复
可以写一个相关的log单例类,log构造函数中做创建一个保存log的文件,再在类中写一个方法,主要是将需要保存的数据写入文件操作,这样的话就能在任何地方调用单例类的方法来将log信息保存到文件中了。如果牵涉到多线程中的log保存问题,则需要在文件操作过程中加入锁的机制。
具体伪代码如下
class Log {
public:
static log* getinstance(){
}
void saveLogToFile(logLevel level, QString logInfo){

private:
Log();
static log *logSingleInstance;
};
ly1chee 2020-03-31
  • 打赏
  • 举报
回复
QMessageLogger
w22net 2020-03-29
  • 打赏
  • 举报
回复
引用 2 楼 亭台六七座 的回复:
[quote=引用 1 楼 w22net 的回复:] 用QFile 创建文件为日志文件,然后再往里写日志。
要在每句代码中插入写日志的代码吗?[/quote] 在需要的地方插吧
亭台六七座 2020-03-29
  • 打赏
  • 举报
回复
引用 1 楼 w22net 的回复:
用QFile 创建文件为日志文件,然后再往里写日志。
要在每句代码中插入写日志的代码吗?
w22net 2020-03-29
  • 打赏
  • 举报
回复
用QFile 创建文件为日志文件,然后再往里写日志。
写在前面的话: 基于HPSocket开发的C/S快速开发框架,引用怪兽群的话“不要怀疑HPSocket,有问题多看DEMO!”,这是对HPSocket稳定高效的最佳诠释!所以,基于HPSocket设计了一些周边功能,方便大家快速开发软件!那么,模块究竟有什么功能呢? 1、数据库连接池: 目前仅支持MYSql数据库,支持设定初始和最大连接数、支持请求超时、支持心跳、支持最大和最小空闲数、支持最大空闲时间检测等等各项功能。至于连接池是用来干什么的,简单的说就是用空间换时间,提前搞N个连接,当有sql请求的时候,从这N个连接中选取空闲连接进行数据库操作。 2、线程池: 这个线程池最大的亮点就是支持线程优先级。啥意思?比如数据库进行增删改操作,又有cha询操作,那么增删改的优先级肯定是要高于cha询优先级的。 3、上传池和下载池: 支持多线程、4G+文件、多客户Duan同时收发,自动分包组包。 4、缓存池: 相信很多人都喜欢用内存搞缓存池,但是搞的多了,回收再不及时的话,容易造成内存泄露。所以,这个缓存池采用临时文件读写方式进行操作,效率虽说逊色内存操作,但是其他方面的优越性是内存缓存池无法比拟的!比如在硬盘空间允许的情况下,缓存池可以无限大,缓存池可以长时间存在,而不用担心内存爆掉的问题。 5、CExcel: 封装了EXCEL相关COM调用方式,命令简洁易懂; 6、CJson: 封装了JS3,支持快速生成和解析JSON文本; 7、参数表: 用于SQL参数化处理!这有啥用?SQL注入攻击相信大家都听过,使用这个方法可以杜绝SQL注入攻击; 8、请求池: 顾名思义,用于处理请求的!这个有啥好说道说道的?规范了请求格式,参数有通信密钥、 协yi头、请求参数、附加数据,支持生成同时含有文本和字节集的请求!另外,请求内部处理了签名问题!啥意思?类似于sign签名,保证请求一致性和完整性。 9、日志池: 支持多线程、多日志同时读写; 10、事件池: 支持多事件同时处理; 11、提示框: 当鼠标悬停在控件上,会跳出提示。封装了tooltips,命令稍微优化了下,更简洁明了。 ············· ⊙﹏⊙b汗,实在吹不下去了,容易被各位大佬XXX·············

16,819

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧