gpt4 book ai didi

c++ - 记录器类的 QFile 和 QTextStream

转载 作者:搜寻专家 更新时间:2023-10-31 01:07:06 24 4
gpt4 key购买 nike

我正在尝试使用 QFile 和 QTextStream 创建一个 Logger 类,但我找不到有效的方法。我只想在其中创建一个 log(...) 函数。

我知道如果我执行以下操作它会起作用:

void CLogger::log(QString strLog,int nType) {
QFile file(m_strFileName);
file.open( QIODevice::Append | QIODevice::Text );
QTextStream logStream(&file);
logStream << nType << "-" << strLog;
file.close();
}

但是它很讨厌。我不想在插入的每一行日志中都创建一个 QFile 对象。

因此,我尝试了几种不同的方法,例如:

1) (以QFile *m_pFile为成员)

CLogger::CLogger()
{
m_pFile = new QFile(m_strFileName);
}
void CLogger::log(QString strLog,int nType)
{
m_pFile->open( QIODevice::Append | QIODevice::Text );
QTextStream logStream(m_pFile);
logStream << nType << "-" << strLog;
m_pFile.close();
}

2) (QFile *m_pFile 和 QTextStream *m_pLogStream 作为成员)

CLogger::CLogger()
{
m_pFile = new QFile(m_strFileName);
m_pFile->open( QIODevice::Append | QIODevice::Text );
m_pLogStream = new QTextStream(m_pFile);
}
void CLogger::log(QString strLog,int nType)
{
*m_pLogStream << nType << "-" << strLog;
}

在第一种情况下,我得到:

C2248: 'QTextStream::QTextStream' : cannot access private member declared in class 'QTextStream'

在第二种情况下,*m_pLogStream 不等同于 QTextStream&。

我做错了什么?

最佳答案

实际上,每次您需要记录某些内容时打开(和关闭)日志文件并不是一个糟糕的解决方案(除非您每秒记录 1000 次......但是没有人能够处理那么多的数据...)。这不仅可以让你拥有一个非常稳定的日志(因为你不会一直打开文件,所以你不依赖于操作系统的刷新),而且还可以让你能够实现如下功能日志滚动和其他细节。

如果您让日志文件保持打开状态,以防发生意外“崩溃”,您可能无法获取所有日志行,这当然取决于您的操作系统如何处理这种不正常的退出。

这是我们用于日志记录的一段代码:

QMutexLocker locker(&m_lineLoggerMutex);

QFile f(getLogFileName());
doRollLogsIfNeeded(static_cast<qint64>(f.size() + lineToBelogged.length()));

// Do not open in append mode but seek() to avoid warning for unseekable
// devices, note that if open is made with WriteOnly without Append, the
// file gets truncated
if (!f.open(QIODevice::ReadWrite | QIODevice::Text))
{
QTextStream out(stdout);
out << "CANNOT OPEN LOG FILE: " << getLogFileName();
return;
}
// seek() does nothing on sequential devices, this is in essence what QFile
// does when Append flag is set in open() but without warning (on Qt 4.8.3)
// However, Qt 4.8.1 issues the warning, so check it explicitly
if (!f.isSequential())
{
f.seek(f.size());
}

QTextStream out(&f);
out << lineToBelogged;

这是一个方法,析构函数负责关闭设备。

关于c++ - 记录器类的 QFile 和 QTextStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19808177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com