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

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

需要写很多 qDebug()吗?
...全文
1051 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
戏言zare 2020-04-24
  • 打赏
  • 举报
回复
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;
};
astro_lee 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 创建文件为日志文件,然后再往里写日志。

16,212

社区成员

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

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