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

标签 c++ qt4 qfile

我正在尝试使用 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/

相关文章:

python - pyqt4:如何显示无模式对话框?

regex - Qt4.8:如何使 QLineEdit 始终以大写显示文本并且仍然具有 RegExp

c++ - QFile.write(myStruct)-怎么样?

qt - 将 QFile 传递给函数

c++ - 为什么 Qt 在 Qt 内部运行或调试时不创建文本文件,而是直接从调试文件夹创建它?

Linux 上的 QtCreator : 32-bits vs. 64 位

c++ - ios::fmtflags如何在C++中工作?setf()如何工作?

c++ - 避免不必要地添加抽象函数以适应新功能的设计模式

c++ - 什么是 undefined symbol : X509_EXTENSION_free?

c++ - 让进程 "warm up"有什么用吗?