In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Getting started with Log4Qt-- Log4Qt log output redirection source code parsing 1, Appender introduction 1, Appender introduction
Appender is an abstract class of all Appender, an abstraction of the form of logging. The inheritance system of Appender in Log4Qt (Qt4 version) is as follows:
2. The Appender interface virtual Filter * filter () const = 0 position virtual QString name () const = 0 politics virtual Layout * layout () const = 0 politics virtual bool requiresLayout () const = 0 politics virtual void setLayout (Layout * pLayout) = 0 politics virtual void setName (const QString & rName) = 0 politics virtual void addFilter (Filter * pFilter) = 0 virtual void clearFilters () = 0 virtual void close () = 0 virtual void doAppend (const LoggingEvent & rEvent) = 0; 2. Introduction to AppenderSkeleton1 and AppenderSkeleton
AppenderSkeleton inherits from the Appender class and implements the general functions of Appender, but it does not implement part of the interface inherited from Appender, so it is still an abstract class and cannot be instantiated. All functions of AppenderSkeleton are thread-safe.
2. AppenderSkeleton interface virtual Filter* filter () const;virtual Layout * layout () const;bool isActive () const;bool isClosed () const;Level threshold () const;virtual void setLayout (Layout * pLayout); virtual void setName (const QString & rName); void setThreshold (Level level); virtual void activateOptions (); virtual void addFilter (Filter* pFilter); virtual void clearFilters (); virtual void close (); virtual void doAppend (const LoggingEvent & rEvent); Filter* firstFilter () const;bool isAsSevereAsThreshold (Level level) const
A custom Appender can be derived from AppenderSkeleton by implementing the following three interfaces:
Virtual void append (const LoggingEvent & rEvent) = 0 * virtual bool requiresLayout () const = 0 * virtual QDebug debug (QDebug & rDebug) const = 0
The append interface is responsible for processing LoggingEvent objects and outputting the formatted log information to different output places, such as text stream, file stream, database, etc. If you need to redirect the log information to the QWidget component, you need to send a signal in the append function, and the log information is used as a signal parameter to receive and process the log information in the slot function of the corresponding QWidget component.
It can also be obtained from WriterAppender, ConsoleAppender,
FileAppender, RollingFileAppender, DailyRollingFileAppender derived classes are implemented.
III. Introduction to WriterAppender1 and WriterAppender
The WriterAppender class inherits from the AppenderSkeleton class and outputs the log information of the LoggingEvent object to the QTextStream object in its implemented append function. All functions of WriterAppender are thread-safe.
Void WriterAppender::append (const LoggingEvent & rEvent) {QString message (layout ()-> format (rEvent)); / / output formatted log information to QTextStream object * mpWriter flush (); if (handleIoErrors ()) return;}} 2, WriterAppender common APIs
QTextCodec * encoding () const
Get the encoder of the output text stream
Bool immediateFlush () const
Gets whether to refresh immediately
QTextStream * writer () const
Get the output text stream object
Void setEncoding (QTextCodec * pTextCodec)
Set the encoder of the text stream
Void setImmediateFlush (bool immediateFlush)
Set whether to refresh immediately
Void setWriter (QTextStream * pTextStream)
Set the output text stream
Virtual void close ()
Close the text stream. If a footer is set, footer information will be printed.
IV. Introduction of ConsoleAppender1 and ConsoleAppender
The ConsoleAppender class inherits from the WriterAppender class, and ConsoleAppender defines the output destinations for both standard output and standard error consoles. All functions of ConsoleAppender are thread-safe.
Enum Target {STDOUT_TARGET,// standard output STDERR_TARGET// standard error}; 2. Implementation of ConsoleAppender log redirection
After ConsoleAppender is configured, its configuration options need to be activated, and the activateOptions function of ConsoleAppender points the text stream to the text stream object of the corresponding console.
Void ConsoleAppender::activateOptions () {QMutexLocker locker (& mObjectGuard); closeStream (); if (mTarget = = STDOUT_TARGET) mpTextStream = new QTextStream (stdout); else mpTextStream = new QTextStream (stderr); / / call setWriter function of WriterAppender, / / redirect log information to the corresponding text stream setWriter (mpTextStream) on the console; WriterAppender::activateOptions ();}
When Logger outputs logs, the formatted log information is output to the corresponding text stream on the console in the append function of WriterAppender to complete the redirection of the output destination.
3. Common APIs for ConsoleAppender
QString target () const
Get output destination
Void setTarget (const QString & rTarget)
Set the rTarget string as the output destination
Void setTarget (Target target)
Set target as the output destination
Virtual void activateOptions ()
Activate options for ConsoleAppender settings
Virtual void close ()
Close ConsoleAppender
4. ConsoleAppender example # include # include int main (int argc, char * argv []) {QCoreApplication a (argc, argv); QThread::currentThread ()-> setObjectName ("MainThread"); / / create TTCCLayout Log4Qt::Logger * logger = Log4Qt::Logger::rootLogger (); Log4Qt::TTCCLayout * layout = new Log4Qt::TTCCLayout (); layout- > setDateFormat ("yyyy-mm-dd hh:mm:ss") / / activate options layout- > activateOptions (); / / create ConsoleAppender Log4Qt::ConsoleAppender * appender = new Log4Qt::ConsoleAppender (); appender- > setLayout (layout); / / set encoding appender- > setEncoding ("UTF-8"); / / set output destination to stdout appender- > setTarget (Log4Qt::ConsoleAppender::STDOUT_TARGET); appender- > setImmediateFlush (true) / / set threshold level to INFO appender- > setThreshold (Log4Qt::Level::INFO_INT); / / Activation option appender- > activateOptions (); logger- > addAppender (appender); / / set level to DEBUG logger- > setLevel (Log4Qt::Level::DEBUG_INT); / / output information logger- > debug ("Hello, Log4Qt!"); logger- > info ("Hello, Qt!") / / close logger logger- > removeAllAppenders (); logger- > loggerRepository ()-> shutdown (); return a.exec ();} / / output:// 2018-03-12 18:03:48 [MainThread] INFO root-Hello, Qt! Brief introduction of FileAppender1 and FileAppender
The FileAppender class inherits from the WriterAppender class and is used to output logs to files.
All functions of FileAppender are thread-safe.
2. The implementation of FileAppender log redirection.
After the FileAppender configuration is completed, the configuration options need to be activated. The specified output file will be opened in the activateOptions function of FileAppender, and the text stream of WriterAppender will be bound to the file stream of the output file to redirect the text stream of WriterAppender to the output file.
Void FileAppender::activateOptions () {QMutexLocker locker (& mObjectGuard); if (mFileName.isEmpty ()) {LogError e = LOG4QT_QCLASS_ERROR (QT_TR_NOOP ("Activation of Appender'% 1' that requires file and has no file set"), APPENDER_ACTIVATE_MISSING_FILE_ERROR); e error (e); return;} closeFile () / / Open the file openFile (); WriterAppender::activateOptions ();} void FileAppender::openFile () {Q_ASSERT_X (mpFile = = 0 & & mpTextStream = = 0, "FileAppender::openFile ()", "Opening file without closing previous file"); QFileInfo file_info (mFileName); QDir parent_dir = file_info.dir () If (! parent_dir.exists ()) {logger ()-> trace ("Creating missing parent directory for file% 1", mFileName); QString name = parent_dir.dirName (); parent_dir.cdUp (); parent_dir.mkdir (name);} mpFile = new QFile (mFileName); QFile::OpenMode mode = QIODevice::WriteOnly | QIODevice::Text / / if (mAppendFile) mode of the configuration file stream | = QIODevice::Append; else mode | = QIODevice::Truncate; if (! mBufferedIo) mode | = QIODevice::Unbuffered If (! mpFile- > open (mode)) {LogError e = LOG4QT_QCLASS_ERROR (QT_TR_NOOP ("Unable to open file'% 1' for appender'% 2'"), APPENDER_OPENING_FILE_ERROR); e error ()); logger ()-> error (e); return } / bind the file stream to the text stream mpTextStream = new QTextStream (mpFile); / / redirect the WriterAppender text stream to the text stream corresponding to the text file stream / / complete the redirection of the output destination setWriter (mpTextStream); logger ()-> debug ("Opened file'% 1' for appender'% 2'", mpFile- > fileName (), name ());}
When Logger outputs the log, the append function of WriterAppender outputs the formatted log information to the output file bound by the text stream, completing the redirection of the output destination.
3. FileAppender interface
Bool appendFile () const
Get whether to append the file
QString file () const
Get the file name of the output destination
Bool bufferedIo () const
Gets whether it is a cache IO
Void setAppendFile (bool append)
Sets whether it is an appended file
Void setBufferedIo (bool buffered)
Sets whether it is cached IO
Void setFile (const QString & rFileName)
Set the file name of the output destination
Virtual void close ()
Close the file
4. FileAppender example
# include # include .h > # include # include int main (int argc, char * argv []) {QCoreApplication a (argc, argv); QThread::currentThread ()-> setObjectName ("MainThread"); / / create TTCCLayout Log4Qt::Logger * logger = Log4Qt::Logger::rootLogger (); Log4Qt::TTCCLayout * layout = new Log4Qt::TTCCLayout (); layout- > setDateFormat ("yyyy-mm-dd hh:mm:ss") / / Activation options layout- > activateOptions (); / / create ConsoleAppender Log4Qt::FileAppender * appender = new Log4Qt::FileAppender; / / set the output destination to logFile.log appender- > setFile ("logFile.log") in the directory where the application resides; appender- > setLayout (layout); / / set encoding appender- > setEncoding ("UTF-8"); appender- > setImmediateFlush (true) / / set threshold level to INFO appender- > setThreshold (Log4Qt::Level::INFO_INT); / / Activation option appender- > activateOptions (); logger- > addAppender (appender); / / set level to DEBUG logger- > setLevel (Log4Qt::Level::DEBUG_INT); / / output information logger- > debug ("Hello, Log4Qt!"); logger- > info ("Hello, Qt!") / / close logger logger- > removeAllAppenders (); logger- > loggerRepository ()-> shutdown (); return a.exec ();} / / logFile:// 2018-06-12 18:06:45 [MainThread] INFO root-Hello, Qt! VI. Brief introduction of RollingFileAppender1 and RollingFileAppender
The RollingFileAppender class inherits from the FileAppender class and is an extension of FileAppender functionality. RollingFileAppender allows rolling backups of log files when the output log files reach the specified size.
All functions of RollingFileAppender are thread-safe.
2. The implementation of RollingFileAppender log redirection.
After the RollingFileAppender configuration is completed, the configuration option needs to be activated. When RollingFileAppender calls the FileAppender::activateOptions function, the specified output file will be opened, and the text stream of WriterAppender will be bound to the file stream of the output file to redirect the text stream of WriterAppender to the output file.
RollingFileAppender implements the append function.
Void RollingFileAppender::append (const LoggingEvent & rEvent) {/ / Q_ASSERT_X (, "RollingFileAppender::append ()", "Lock must be held by caller") / / use FileAppender to bind the output file to WidgetAppender's output text stream FileAppender::append (rEvent) / / if the log file size is greater than the maximum specified by the log file, perform a roll backup operation if (writer ()-> device ()-> size () > this- > mMaximumFileSize) backup ();}
When Logger makes log output, RollingFileAppender uses the FileAppender::append (actually WriterAppender::append) function to output the formatted log information to the output file bound by the text stream, completing the redirection of the output destination. A roll backup operation occurs if the size of the output file is greater than the specified maximum value.
3. RollingFileAppender interface
Int maxBackupIndex () const
Get maximum backup index
Qint64 maximumFileSize () const
Gets the maximum output log file size
Void setMaxBackupIndex (int maxBackupIndex)
Set the maximum index of backup files
Void setMaximumFileSize (qint64 maximumFileSize)
Set the maximum value of a single output log file to maximumFileSize bytes
Void setMaxFileSize (const QString & rMaxFileSize)
Set the maximum value of a single output log file to the value of rMaxFileSize. You can use units such as KB,MB,GB.
4. RollingFileAppender example # include # include .h > .h > # include # include int main (int argc, char * argv []) {QCoreApplication a (argc, argv); QThread::currentThread ()-> setObjectName ("MainThread"); / / create TTCCLayout Log4Qt::Logger * logger = Log4Qt::Logger::rootLogger (); Log4Qt::TTCCLayout * layout = new Log4Qt::TTCCLayout (); layout- > setDateFormat ("yyyy-mm-dd hh:mm:ss") / / activate the option layout- > activateOptions (); / / create ConsoleAppender Log4Qt::RollingFileAppender * appender = new Log4Qt::RollingFileAppender; / / set the output destination to logFile.log appender- > setFile ("logFile.log") in the directory where the application resides; / / set the log to write to the output file appender- > setAppendFile (true) in append mode. / / set the maximum number of backup files to 10 appender- > setMaxBackupIndex (10); / / set the maximum output file to 1KB appender- > setMaxFileSize ("1KB"); appender- > setLayout (layout); / / set encoding appender- > setEncoding (QTextCodec::codecForName ("UTF-8")); appender- > setImmediateFlush (true); / / set the threshold level to INFO appender- > setThreshold (Log4Qt::Level::INFO_INT) / / Activation options appender- > activateOptions (); logger- > addAppender (appender); / / set the level to DEBUG logger- > setLevel (Log4Qt::Level::DEBUG_INT); / / output information for (int I = 0; I
< 100; i++) { logger->Debug ("Hello, Log4Qt!"); logger- > info ("Hello, Qt!");} / / close logger logger- > removeAllAppenders (); logger- > loggerRepository ()-> shutdown (); return a.exec ();}
The most recent log of the program is output to logFile.log, and five files are backed up, namely logFile.log.1, logFile.log.2, logFile.log.3, logFile.log.4, logFile.log.5
Brief introduction of DailyRollingFileAppender1 and DailyRollingFileAppender
The DailyRollingFileAppender class inherits from the FileAppender class and is an extension of FileAppender functionality. DailyRollingFileAppender allows exported log files to be rolled back up at a specified frequency.
All functions of DailyRollingFileAppender are thread-safe.
DailyRollingFileAppender defines six date modes.
Enum DatePattern {MINUTELY_ROLLOVER = 0 MINUTELY_ROLLOVER / min, 'yyyy-MM-dd-hh-mm' HOURLY_ROLLOVER,// hourly, yyyy-MM-dd-hh HALFDAILY_ROLLOVER,// every half day, yyyy-MM-dd-a DAILY_ROLLOVER,// daily, yyyy-MM-dd WEEKLY_ROLLOVER,// weekly, yyyy-ww MONTHLY_ROLLOVER// monthly, yyyy-MM}; 2. Implementation of DailyRollingFileAppender log redirection
After the configuration of DailyRollingFileAppender is completed, you need to activate its configuration options. The activateOptions function of DailyRollingFileAppender calculates the frequency of rollback of the output file, and calls the FileAppender::activateOptions () function to bind the text stream of WriterAppender to the file stream of the output file to redirect the text stream of WriterAppender to the output file.
Void DailyRollingFileAppender::activateOptions () {QMutexLocker locker (& mObjectGuard); / / calculate the frequency of output file rollback, computeFrequency (); if (! mActiveDatePattern.isEmpty ()) {/ / calculate the time of output file rollback computeRollOverTime (); / / call FileAppender::activateOptions to redirect the output text stream to the output file FileAppender::activateOptions ();}}
DailyRollingFileAppender implements the append function.
Void DailyRollingFileAppender::append (const LoggingEvent & rEvent) {/ / if the current time is greater than the output file rollback time, roll back the output file if (QDateTime::currentDateTime () > mRollOverTime) rollOver (); / / call FileAppender::append to output the formatted log to the output file FileAppender::append (rEvent);}
When Logger makes log output, DailyRollingFileAppender processes the LoggingEvent object within the append function. If the current time is greater than the time required for the output file to be rolled back, DailyRollingFileAppender performs a rollback backup of the output file and creates a new log output file. The FileAppender::append function is then called to output the formatted log to the specified output file.
3. DailyRollingFileAppender interface
QString datePattern () const
Get date matching pattern string
Void setDatePattern (DatePattern datePattern)
Set date matching mode
Void setDatePattern (const QString & rDatePattern)
Set rDatePattern to date matching mode
4. DailyRollingFileAppender example # include # include > # include # include int main (int argc, char * argv []) {QCoreApplication a (argc, argv); QThread::currentThread ()-> setObjectName ("MainThread"); / / create TTCCLayout Log4Qt::Logger * logger = Log4Qt::Logger::rootLogger (); Log4Qt::TTCCLayout * layout = new Log4Qt::TTCCLayout (); layout- > setDateFormat ("yyyy-mm-dd hh:mm:ss") / / activate options layout- > activateOptions (); / / create ConsoleAppender Log4Qt::DailyRollingFileAppender * appender = new Log4Qt::DailyRollingFileAppender; / / set the output destination to logFile.log appender- > setFile ("logFile.log") in the directory where the application resides; / / set log files to be rolled back every day / / appender- > setDatePattern (Log4Qt::DailyRollingFileAppender::MINUTELY_ROLLOVER) Appender- > setDatePattern ("'. 'yyyy-MM-dd-hh-mm"); / / set log to write output file appender- > setAppendFile (true); appender- > setLayout (layout); / / set encoding appender- > setEncoding ("UTF-8"); appender- > setImmediateFlush (true); / / set threshold level to INFO appender- > setThreshold (Log4Qt::Level::INFO_INT) / / Activation options appender- > activateOptions (); logger- > addAppender (appender); / / set the level to DEBUG logger- > setLevel (Log4Qt::Level::DEBUG_INT); / / output information for (int I = 0; I
< 10; i++) { logger->Debug ("Hello, Log4Qt!"); logger- > info ("Hello, Qt!"); for (int I = 0; I
< 1000000000; i++) ; logger->Debug ("Hello, Log4Qt2!"); logger- > info ("Hello, Qt2!");} / / close logger logger- > removeAllAppenders (); logger- > loggerRepository ()-> shutdown (); return a.exec ();}
When the program is executed, the log is output to logFile.log, and the output log is rolled back every minute. The backup file name is as follows: logFile.log.2018-10-12-18-30.
8. Redirect log to QWidget1 and Log4Qt source code import
Copy the src/log4qt directory under the Log4Qt source code project into your own project, and add the following configuration to your own project file:
# define the required macro definitions + = LOG4QT_LIBRARY# copy the src/log4qt directory under the Log4Qt source project into your own project src directory # define the Log4Qt source root directory LOG4QT_ROOT_PATH = $PWD/log4qt# specify the # include directory that should be searched when compiling the project INCLUDEPATH + = $LOG4QT_ROOT_PATH# add the Log4Qt source code to the project include ($LOG4QT_ROOT_PATH/log4qt.pri) 2, WidgetAppender implementation
WidgetAppender is implemented from AppenderSkeleton.
WidgetAppender.h file:
# ifndef WIDGETAPPENDER_H#define WIDGETAPPENDER_H#include # include # include "appenderskeleton.h" # include namespace Log4Qt {/ * @ brief WidgetAppender inherits from the AppenderSkeleton class and is used to redirect log information to the QWidget component * @ author scorpio * @ note WidgetAppender Note: * 1. You must use the setLogWidget API to set the redirection location of the log information. That is, the output window component * 2, a slot function onAppendLog (const QString& msg) must be implemented to receive the logAppend (const QString& msg) signal sent by WidgetAppender *. The parameter msg is the received log information, and the output window component * needs to output msg to the corresponding form. * / class WidgetAppender: public AppenderSkeleton {Q_OBJECTpublic: WidgetAppender (QObject * parent = NULL); ~ WidgetAppender (); / * @ brief set the QWidget component for log information output * @ param widget, input parameters, log information output window, need developers to implement * / void setLogWidget (const QWidget& widget) Signals: / * @ brief adds a new log message signal * @ param msg. Input parameters, formatted log information * @ note logAppend signal is received by the QWidget output window component. Developers need to implement the * slot function onAppendLog (const QString& msg) in the output window component. * / void logAppend (const QString& msg); protected: virtual bool requiresLayout () const; virtual void append (const Log4Qt::LoggingEvent & rEvent); # ifndef QT_NO_DEBUG_STREAM virtual QDebug debug (QDebug & rDebug) const;#endif / / QT_NO_DEBUG_STREAMprivate: QWidget * masked logWidget;};} # endif / / WIDGETAPPENDER_H
WidgetAppender.cpp file:
# include "WidgetAppender.h" # include "loggingevent.h" # include namespace Log4Qt {WidgetAppender::WidgetAppender (QObject * parent): AppenderSkeleton (parent) {m_logWidget = NULL;} WidgetAppender::~WidgetAppender () {} void WidgetAppender::setLogWidget (const QWidget & widget) {m_logWidget = const_cast (& widget); / / onAppendLog (const QString&) slot function connect (this, SIGNAL (logAppend (const QString&)), m_logWidget, SLOT (onAppendLog (const QString&)) } bool WidgetAppender::requiresLayout () const {return true;} void WidgetAppender::append (const LoggingEvent & rEvent) {/ / format log information QString message = dynamic_cast (layout ())-> format (rEvent); emit logAppend (message);} # ifndef QT_NO_DEBUG_STREAMQDebug WidgetAppender::debug (QDebug & rDebug) const {return rDebug.space ();} # endif / / QT_NO_DEBUG_STREAM} 3, QWidget output window implementation
Widget.h file:
# ifndef WIDGET_H#define WIDGET_H#include # include class Widget: public QWidget {Q_OBJECTpublic: Widget (QWidget * parent = 0); ~ Widget (); private slots: / * @ brief slot function to receive log information * @ param log, enter parameters, formatted log information * / void onAppendLog (const QString& log); private: QTextEdit* masked logEdit; QMutex masked log text;} # endif / / WIDGET_H
Widget.cpp file:
# include "Widget.h" Widget::Widget (QWidget * parent): QWidget (parent) {m_logEdit = new QTextEdit (); QVBoxLayout* layout = new QVBoxLayout; layout- > addWidget (m_logEdit); setLayout (layout); resize (600,400);} Widget::~Widget () {} void Widget::onAppendLog (const QString & log) {QMutexLocker lock (& m_mutex); / / output log information to the window component masked logEdit-> insertPlainText (log) 4. Application example # include "Widget.h" # include # include int main (int argc, char * argv []) {QApplication a (argc, argv); Widget w; w.show (); Log4Qt::BasicConfigurator::configure (); Log4Qt::LogManager::setHandleQtMessages (true); Log4Qt::Logger * logger = Log4Qt::Logger::rootLogger (); logger- > removeAllAppenders (); Log4Qt::WidgetAppender * appender = new Log4Qt::WidgetAppender () Appender- > setName ("WidgetAppender"); Log4Qt::TTCCLayout * layout = new Log4Qt::TTCCLayout (Log4Qt::TTCCLayout::ISO8601); layout- > setThreadPrinting (true); appender- > setLayout (layout); appender- > activateOptions (); / / set the window components for log information output appender- > setLogWidget (w); logger- > addAppender (appender); logger- > warn ("hello Log4Qt"); logger- > info ("hello Log4Qt"); logger- > debug ("hello Log4Qt") Logger- > info ("Hello Log4Qt"); logger- > removeAllAppenders (); return a.exec ();} / / output:// 2018-10-09 10 Log4Qt 27 DEBUG root 18.542 [] WARN root-hello Log4Qt// 2018-10-09 10 Fran 18.542 [] INFO root-hello Log4Qt// 2018-10-09 10 purl 2718.542 [] DEBUG root-hello Log4Qt// 2018-10-09 10 Fringe 27 Log4Qt []
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.