In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
Getting started with Log4Qt-- Log4Qt log formatting source code parsing I. introduction to Layout1 and Layout
Log4Qt provides a variety of Layout objects for formatting log output, specifying log level, thread name, Logger name, date and time, and so on.
The Layout class is an abstract class in Log4Qt API.
PatternLayout: outputs log events based on a pattern string
SimpleLayout: output the level and message of log events
TTCCLayout: outputs the time of the log event, thread name, Logger name, and nested diagnostic context information.
PatternLayout and TTCCLayout are formatted through PatternFormatter. When PatternFormatter parses a schema string, a PatternConverter chain is created based on the information found, and each PatternConverter processes a member of the LoggingEvent.
Conversion characters: used to specify the type of data, such as category, level, date, thread name. The converted characters in Log4Qt are:
C:Logger name.
D {format_string}: date. The parameter format_string is optional and is used to format the date.
M: message content
P: message level
R: relative time to start the program
T: thread name
X:NDC (nested diagnostic context) name
X:MDC (mapped Diagnostic context) name
F: file name
M: method name
L: line number
L: location information
N: platform-related line delimiters, Windows:\ r\ nPersonLinux:\ n
2. Introduction to NDC
NDC (Nested Diagnostic Context), that is, nested diagnostic context, is a class used by log4J to store context information (context information). NDC adopts stack mechanism push and pop context, and each thread has an independent context. If the context information to be stored is stack, choose NDC.
Common APIs for NDC are as follows:
Static QString pop ()
Pop up the top element of the NDC stack
Static void push (const QString & rMessage)
Push rMessage onto the NDC stack
Static void clear ()
Clear the NDC stack
Static int depth ()
Get the depth of the NDC stack
Static void setMaxDepth (int maxDepth)
Set the maximum depth of the NDC stack
Static QString peek ()
Get the data at the top of the NDC stack
Usually, the thread-related application information is saved in the context or servlet entry, and the information is output when the log log information is needed, and it is guaranteed to use clear () to remove it at the end of the current thread or at the exit of the servlet to prevent information leakage.
3. Introduction to MDC
MDC (Mapped Diagnositc Context), that is, mapping diagnostic context, is a class used by log4J to store context information (context information). MDC is implemented internally by Hash container and is thread-independent, but a child thread will automatically get a copy of a parent thread MDC. If the context information to be stored is a key/value-style choice MDC.
Common APIs for MDC are as follows:
Static void put (const QString & rKey, const QString & rValue)
Store rKey/rValue data in a Hash container
Static void remove (const QString & rKey)
Delete a key/value whose key is rKey from the Hash container
Static QString get (const QString & rKey)
Get the key/value whose key is rKey from the Hash container
Static QHash context ()
Get all the contents in the Hash container
4. Common APIs for Layout
QString footer () const
Get the footer of the Layout object
QString header () const
Get the header of the Layout object
QString name () const
Gets the object name of the Layout object
Void setFooter (const QString & rFooter)
Set the footer of the Layout object
Void setHeader (const QString & rHeader)
Set the header of the Layout object
Void setName (const QString & rName)
Sets the object name of the Layout object
Virtual QString format (const LoggingEvent & rEvent) = 0
The log message formatting interface of the Layout object, and the derived classes PatternLayout, SimpleLayout, and TTCCLayout determine the format of the specific information to be output through the format function.
II. Introduction of PatternLayout1 and PatternLayout
PatternLayout is a derivative of Layout, and if you want to generate log information in a specific format based on pattern matching, you can use PatternLayout for formatting.
PatternLayout's enumeration ConversionPattern defines two common patterns:
Enum ConversionPattern {DEFAULT_CONVERSION_PATTERN,// "% m department% n" TTCC_CONVERSION_PATTERN,// "% r [% t]% p% c% x -% m% n"}; 2. PatternLayout common APIs
QString conversionPattern () const
Gets the translation pattern matching string for the PatternLayout object
Void setConversionPattern (const QString & rPattern)
Set the translation pattern matching string for the PatternLayout object
Void setConversionPattern (ConversionPattern conversionPattern)
Sets the translation pattern matching method for PatternLayout objects
3. Format format QString PatternLayout::format (const LoggingEvent & rEvent) {Q_ASSERT_X (mpPatternFormatter, "PatternLayout::format ()", "mpPatternConverter must not be null"); return mpPatternFormatter- > format (rEvent);}
Call the PatternFormatter format function to format the information based on each pattern converter in the linked list of pattern converters.
QString PatternFormatter::format (const LoggingEvent & rLoggingEvent) const {QString result; PatternConverter * pendant converter; Q_FOREACH (p_converter, mPatternConverters) pendant converter-> format (result, rLoggingEvent); return result;}
PatternFormatter uses pattern matching strings to create a pattern converter mPatternConverters, each corresponding to a pattern converter.
Void PatternFormatter::createConverter (const QChar & rChar, const FormattingInfo & rFormattingInfo, const QString & rOption) {Q_ASSERT_X (mConversionCharacters.indexOf (rChar) > = 0, "PatternFormatter::createConverter", "Unknown conversion character") LogError e ("Creating Converter for character'1' min 2, max 3, left 4 and option'5'"); e shutdown (); return a.exec () } / / output://-start-/ / 2018-10-11 21:25:30 [DEBUG]-Debug, Log4QtCompact / 2018-10-11 21:25:30 [INFO]-Info, Log4QtUniple /-end-5, configure PatternLayout
Use the log4qt.properties configuration file to configure PatternLayout:
# define rootLoggerlog4j.rootLogger=DEBUG Console# defines ConsoleAppenderlog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.immediateFlush=truelog4j.appender.console.target=STDOUT_TARGET# as ConsoleAppender defines Layoutlog4j.appender.console.layout=org.apache.log4j.PatternLayoutlog4j.appender.console.layout.header=- start-log4j.appender.console.layout.footer=- end-log4j.appender.console.layout.conversionPattern=%d {yyyy-MM-dd hh:mm:ss} [% t]% p% c% x -% m% n
Examples of program usage:
# include # include int main (int argc, char * argv []) {QCoreApplication a (argc, argv); QThread::currentThread ()-> setObjectName ("MainThread"); / / get rootLogger Log4Qt::Logger* logger = Log4Qt::Logger::rootLogger (); / / print message logger- > debug ("Debug, Log4Qt!"); logger- > info ("Info, Log4Qt!"); / / close rootLogger logger- > removeAllAppenders () Logger- > loggerRepository ()-> shutdown (); return a.exec ();} / / output://-start-/ / 2018-10-11 21:35:58 [MainThread] DEBUG root-Debug, Log4Qtsteps / 2018-10-11 21:35:58 [MainThread] INFO root-Info, introduction to Log4Qtbrands /-end-III, SimpleLayout1, SimpleLayout
SimpleLayout is a derivative of Layout, and the formatting of log messages includes only the level of the log and the content of the message.
2. Format format to implement QString SimpleLayout::format (const LoggingEvent & rEvent) {return rEvent.level (). ToString () + QLatin1String ("-") + rEvent.message () + Layout::endOfLine ();}
The formatting of log messages by SimpleLayout contains only the level of the log and the content of the message.
3. SimpleLayout example # include # include int main (int argc, char * argv []) {QCoreApplication a (argc, argv); / / create SimpleLayout Log4Qt::Logger * logger = Log4Qt::Logger::rootLogger (); Log4Qt::SimpleLayout * layout = new Log4Qt::SimpleLayout (); layout- > setFooter ("end"); layout- > setHeader ("start"); layout- > activateOptions () / create ConsoleAppender Log4Qt::ConsoleAppender * appender = new Log4Qt::ConsoleAppender (layout, Log4Qt::ConsoleAppender::STDOUT_TARGET); appender- > activateOptions (); logger- > addAppender (appender); logger- > setLevel (Log4Qt::Level::DEBUG_INT); logger- > debug ("Debug, Log4Qt!"); logger- > info ("Info, Log4Qt!"); / / close logger logger- > removeAllAppenders (); logger- > loggerRepository ()-> shutdown () Return a.exec ();} / / output:// start// DEBUG-Debug, Log4Qt Info / INFO-Info, Log4Qt Info / end4, configuration SimpleLayout
Use the log4qt.properties configuration file to configure SimpleLayout:
# define rootLoggerlog4j.rootLogger=DEBUG, console# define ConsoleAppenderlog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.immediateFlush=truelog4j.appender.console.target=STDOUT_TARGET#, define Layoutlog4j.appender.console.layout=org.apache.log4j.SimpleLayoutlog4j.appender.console.layout.header=- start-log4j.appender.console.layout.footer=- end-for ConsoleAppender
Examples of program usage:
# include # include # include int main (int argc, char * argv []) {QCoreApplication a (argc, argv); / get rootLogger Log4Qt::Logger* logger = Log4Qt::Logger::rootLogger (); / / print message logger- > debug ("Hello, Log4Qt!"); logger- > info ("Hello, Log4Qt!"); / / close rootLogger logger- > removeAllAppenders (); logger- > loggerRepository ()-> shutdown (); return a.exec () } / / output://-start-/ / DEBUG-Hello, INFO-Hello, TTCCLayout1-Hello, TTCCLayout1-IV, TTCCLayout1-IV
TTCCLayout is a derived class of Layout and is responsible for providing detailed information about log events, usually including the following:
Time: the time in milliseconds since the application was started
Thread: calling thread
Category: the category or Logger used to create log events
Context:NDC information. NDC information is not automatically included in the LoggingEvent object and must specifically contain NDC information. Therefore, Context is an optional output of TTCCLayout, and even if the NDC setting is enabled, TTCCLayout may not display any NDC data if the LoggingEvent does not contain any NDC settings.
TTCCLayout has several optional parameters, but even if no options are set, TTCCLayout still outputs the following information:
Level: the level of log messages
Message: the log message itself.
TTCCLayout predefines a variety of date formats, as follows:
Enum DateFormat {NONE,// has no date format ISO8601,// yyyy-MM-dd hh:mm:ss.zzz ABSOLUTE,// HH:mm:ss.zzz DATE,//MMM YYYY HH:mm:ss.zzzz RELATIVE / / the number of milliseconds at the beginning of program startup}; 2. TTCCLayout common APIs
Bool categoryPrefixing () const
Gets whether to format the output Logger name
Bool contextPrinting () const
Get whether to format the output NDC information
QString dateFormat () const
Get a string in date format
Bool threadPrinting () const
Gets whether to format the output thread name
Void setCategoryPrefixing (bool categoryPrefixing)
Sets whether the specified Logger name is formatted output.
Void setContextPrinting (bool contextPrinting)
Sets whether to format the output NDC information
Void setDateFormat (const QString & rDateFormat)
Format the date represented by the rDateFormat string
Void setDateFormat (DateFormat dateFormat)
Sets the date format type defined by the DateFormat enumeration type
Void setThreadPrinting (bool threadPrinting)
Sets whether to format the output thread name
Virtual QString format (const LoggingEvent & rEvent)
Format log information interface
Static void Log4Qt::NDC::push (const QString & rMessage)
Push rMessage information into the NDC stack
Static QString Log4Qt::NDC::pop ()
Remove the information from the top of the NDC stack
3. Format format QString TTCCLayout::format (const LoggingEvent & rEvent) {Q_ASSERT_X (mpPatternFormatter, "TTCCLayout::format ()", "mpPatternConverter must not be null"); return mpPatternFormatter- > format (rEvent);}
The formatting of TTCCLayout is the same as that of PatternLayout, with each pattern converter formatting information in the linked list of pattern converters created based on the pattern matching string.
4. TTCCLayout example # include # include int main (int argc, char * argv []) {QCoreApplication a (argc, argv); QThread::currentThread ()-> setObjectName ("MainThread"); Log4Qt::Logger * logger = Log4Qt::Logger::rootLogger (); / / create TTCCLayout Log4Qt::TTCCLayout * layout = new Log4Qt::TTCCLayout (); layout- > setDateFormat ("yyyy-mm-dd hh:mm:ss"); layout- > activateOptions () / / create a ConsoleAppender Log4Qt::ConsoleAppender * appender = new Log4Qt::ConsoleAppender (layout, Log4Qt::ConsoleAppender::STDOUT_TARGET); appender- > activateOptions (); logger- > addAppender (appender); logger- > setLevel (Log4Qt::Level::DEBUG_INT); / / NDC information Log4Qt::NDC::push ("Thread start"); logger- > debug ("Hello, Log4Qt!"); Log4Qt::NDC::pop () Logger- > info ("Hello, Log4Qt!"); / / close logger logger- > removeAllAppenders (); logger- > loggerRepository ()-> shutdown (); return a.exec ();} / / output:// 2018-18-11 23:18:12 [MainThread] DEBUG root Thread start-Hello, Log4QtExample / 2018-18-11 23:18:12 [MainThread] INFO root-Hello, Log4QtSecret5, configure TTCCLayout
Use the log4qt.properties configuration file to configure TTCCLayout:
# define rootLoggerlog4j.rootLogger=DEBUG, console# define ConsoleAppenderlog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.immediateFlush=truelog4j.appender.console.target=STDOUT_TARGET#, define Layoutlog4j.appender.console.layout=org.apache.log4j.TTCCLayoutlog4j.appender.console.layout.categoryPrefixing=truelog4j.appender.console.layout.contextPrinting=truelog4j.appender.console.layout.threadPrinting=truelog4j.appender.console.layout.dateFormat=ISO8601 for ConsoleAppender
Examples of program usage:
# include # include int main (int argc, char * argv []) {QCoreApplication a (argc, argv); QThread::currentThread ()-> setObjectName ("MainThread"); Log4Qt::Logger * logger = Log4Qt::Logger::rootLogger (); / / NDC Information Log4Qt::NDC::push ("Thread start"); logger- > debug ("Hello, Log4Qt!"); Log4Qt::NDC::pop () Logger- > info ("Hello, Log4Qt!"); / / close logger logger- > removeAllAppenders (); logger- > loggerRepository ()-> shutdown (); return a.exec ();} / / output:// 2018-10-11 2322 output:// 09.936 [MainThread] DEBUG root Thread start-Hello, Log4Qthands / 2018-10-11 2322 MainThread INFO root-Hello, 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.