Stream Logger class recommendations? [SOLVED]



  • Hi,

    I am attempting to write a simple logging class (It will be useful between all of my projects). What I would like to do is just create a time stamped file and stream data into the log file class like qDebug() does in the command window but into a file instead. There are some general log streaming c++ classes I found online but I didn't know if anyone has done this with Qt libraries yet?

    Basically, I would like to have an enum for all the different types of log levels and allow the level to be included in the log call like so:
    @
    enum LogLevels {
    LOG_INFO = 0,
    LOG_DEBUG,
    LOG_ERROR
    // there probably would be much more
    }

    // class setup
    Logger Log;
    Log.setFileName("mylog.log");

    // stream data into the file
    Log(LOG_INFO) << "example of streaming log text into class";

    // or possible like this
    Log << LOG_INFO << "example of streaming log text into class";

    // or with other inputs
    int number_example = 100;
    Log(LOG_INFO) << QString("example of a different object with a number appended ") << number_example;
    @

    Basic c++ logger stream I found online:
    @
    class Logger
    {
    public:
    // constructor
    Logger(std::string filename, std::ostream* stream)
    {
    if (stream)
    o_stream = stream;
    }

    // destructor
    virtual ~Logger()
    {
        o_stream->close();
        delete o_stream;
    }
    
    // stream in template
    template<typename T>
    Logger& operator << (const T& object)
    {
        (*o_stream) <&lt; object;
        return *this;
    }
    

    private:
    std::ostream *o_stream;

    };
    @

    I thought it might be an interesting topic since I am not sure what the best Qt classes would be to use (QTextStream? QDataStream?)?


  • Lifetime Qt Champion

    Hi,

    Have a look at "Debug documentation":http://qt-project.org/doc/qt-4.8/debug.html and specially "qInstallMsgHandler":http://qt-project.org/doc/qt-4.8/qtglobal.html#qInstallMsgHandler

    That would be a good start to integrate your logging class with Qt.

    If you want to write a text file QTextStream is a good way to go. On the other hand, if you would like some ready made solution, there's KDAB's KDLog from their KDTools package that offers interesting possibilities to also interact with the platform logging frameworks.

    Hope it helps



  • Thank you! it did indeed. I am setting up the log levels and will post when I am done. I did end up using QTextStream for the output stream. Thanks!


  • Lifetime Qt Champion

    You're welcome !

    Don't forget to set the thread's title to solved so other forum users may know that a solution has been found :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.