【问题标题】:QFile and QTextStream for a logger class记录器类的 QFile 和 QTextStream
【发布时间】:2013-11-06 09:25:18
【问题描述】:

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

我做错了什么?

【问题讨论】:

    标签: c++ qt4 qfile


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      相关资源
      最近更新 更多