2

我正在尝试使用 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”:无法访问在“QTextStream”类中声明的私有成员

第二,*m_pLogStream 不等同于 QTextStream&。

我究竟做错了什么?

4

1 回答 1

4

实际上,每次需要记录某些内容时打开(和关闭)日志文件并不是一个糟糕的解决方案(除非您每秒记录 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;

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

于 2013-11-06T09:40:27.953 回答