在我的服务器应用程序中,我正在创建一个大小为5kb的日志文件。如果我超过5 kb的文件大小,我必须借助新内容覆盖旧内容。 如果您有任何想法,请与我分享。
我还需要在 qt 中实现这项技术。
我在c ++中发现了一些例子,但是使用我不熟悉的boost库,你可以帮助我在qt中实现。
std::ostream & libLogging::FileRotationLogSink::GetCurrentStream(
std::string::size_type required )
{
if ( static_cast<std::string::size_type>(m_CurrentStream.tellp( )) +
required > m_Limit ) {
m_CurrentStream.close();
// remove old backup
if ( boost::filesystem::exists( m_BackupPath ) ) {
boost::filesystem::remove( m_BackupPath );
}
// backup current logfile
boost::filesystem::rename( m_LogFilePath, m_BackupPath );
// open new logfile
m_CurrentStream.open( m_LogFilePath );
}
return m_CurrentStream;
}
答案 0 :(得分:1)
示例实现:
#ifndef FILEROTATIONLOGSINK_H
#define FILEROTATIONLOGSINK_H
#include <QFile>
#include <QTextStream>
namespace libLogging {
class FileRotationLogSink
{
public:
explicit FileRotationLogSink(size_t Limit = 5 * (1 << 10));
QTextStream &GetCurrentStream(size_t required = 0);
private:
size_t m_Limit;
QString m_LogFilePath, m_BackupPath;
QTextStream m_CurrentStream;
QFile m_File;
void openStream();
};
}
#endif // FILEROTATIONLOGSINK_H
与相关的cpp
#include "FileRotationLogSink.h"
libLogging::FileRotationLogSink::FileRotationLogSink(size_t Limit) :
m_Limit(Limit),
m_LogFilePath("log"),
m_BackupPath("bak")
{
m_File.setFileName(m_LogFilePath);
m_File.open(QIODevice::WriteOnly | QIODevice::Text);
m_CurrentStream.setDevice(&m_File);
}
QTextStream& libLogging::FileRotationLogSink::GetCurrentStream(size_t required) {
if (m_File.size() + required > m_Limit) {
m_File.flush();
m_File.close();
// remove old backup
if (QFile::exists(m_BackupPath))
QFile::remove(m_BackupPath);
// backup current logfile
QFile::rename(m_LogFilePath, m_BackupPath);
m_File.open(QIODevice::WriteOnly | QIODevice::Text);
}
return m_CurrentStream;
}
使用示例:
#include "mainwindow.h"
#include "FileRotationLogSink.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
libLogging::FileRotationLogSink log(100);
for (int i = 0; i < 100; ++i)
log.GetCurrentStream() << "line " << i << endl;
}
以日志
收益line 92
line 93
line 94
line 95
line 96
line 97
line 98
line 99
和bak
line 79
line 80
line 81
line 82
line 83
line 84
line 85
line 86
line 87
line 88
line 89
line 90
line 91
答案 1 :(得分:0)
您可以将boost::filesystem::<functions>
替换为QFile::<functions>
。查看文档以查看用法和确切签名。