c++ - how to limit log size in Qt -


in server application i'm creating log file of size 5kb. if exceeds 5 kb of file size , have overwrite old contents of new contents. if have ideas share me.

i need implementation of technique in qt.

i've found out examples in c++, using boost library, i'm not familiar, can me on implementation in 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; } 

example implementation:

#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 

with related 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; } 

example use:

#include "mainwindow.h" #include "filerotationlogsink.h"  mainwindow::mainwindow(qwidget *parent)     : qmainwindow(parent) {     liblogging::filerotationlogsink log(100);     (int = 0; < 100; ++i)         log.getcurrentstream() << "line " << << endl; } 

yields in log

line 92 line 93 line 94 line 95 line 96 line 97 line 98 line 99 

and in 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 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -