LOG4QT Quick Start--LOG4QT log format source parsing

Source: Internet
Author: User
Tags dateformat

LOG4QT Quick Start--LOG4QT log format source parsing first, LAYOUT1, layout introduction

LOG4QT provides a variety of layout objects for formatting log output, specifying log level, thread name, logger name, DateTime, and more.

The layout class is an abstract class in the LOG4QT API.
Patternlayout: Output Log events According to a pattern string;
Simplelayout: The level and message of the output log event;
Ttcclayout: The time of the output log event, the thread name, the logger name, and the nested diagnostic context information.
Patternlayout and Ttcclayout are formatted by Patternformatter. When Patternformatter parses a pattern string, a Patternconverter chain is created based on the information found, and each patternconverter processes a member of Loggingevent.
Convert character: Used to specify the type of data, for example: category, level, date, thread name. The conversion characters in LOG4QT are:
C:logger name.
D{format_string}: Date. Parameter format_string? Optional, used to format the date.
M: Message Content
P: Message Level
R: The relative time of the startup 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-dependent row delimiter, windows:\r\n,linux:\n

2. About NDC

NDC (Nested Diagnostic context) is a nested diagnostic context, a class log4j used to store contextual information (context information), and NDC uses the mechanism push and pop contexts of the stack, with each thread having a separate context, If the context information to be stored is stacked in the select NDC.
NDC commonly used interfaces are as follows:
static QString pop();
Eject the top element of the NDC stack
static void push(const QString &rMessage);
Press rmessage into 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 data on the top of the NDC stack
The thread-related application information is usually saved in the context or Servlet portal, and the information is output when logging log information is required, and is guaranteed to be removed at the end of the current thread or at the exit of the servlet using clear () to prevent information disclosure.

3. Introduction of MDC

The MDC (Mapped DIAGNOSITC context), the mapping diagnostic context, is the class that log4j uses to store contextual information (context information), which is implemented in a hash container internally and is thread independent. But a child thread will automatically get a parent thread for the MDC copy, if the context information to be stored is key/value-type selection MDC.
The MDC common interfaces are as follows:
static void put(const QString &rKey, const QString &rValue);
Storing rkey/rvalue data in a hash container
static void remove(const QString &rKey);
Remove key rkey from the hash container key/value
static QString get(const QString &rKey);
Get the key to Rkey from the hash container key/value
static QHash<QString, QString> context();
Get all the content in the hash container

4. Layout Common Interface

QString footer() const;
Gets the footer of the layout object
QString header() const;
Gets 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);
To set the header of a layout object
void setName(const QString &rName);
Set the object name of the layout object
virtual QString format(const LoggingEvent &rEvent) = 0;
The log Message format interface for the layout object, derived classes Patternlayout, Simplelayout, and ttcclayout are formatted with the Format function to determine the specific output information.

Ii. Introduction to PATTERNLAYOUT1 and Patternlayout

Patternlayout is a derived class for layout and can be formatted using patternlayout if you want to generate log information in a specific format based on pattern matching.
The enumeration Conversionpattern for Patternlayout defines two commonly used patterns:

enum ConversionPattern{    DEFAULT_CONVERSION_PATTERN,// "%m,%n"    TTCC_CONVERSION_PATTERN,//"%r [%t] %p %c %x - %m%n"};
2, Patternlayout Common interface

QString conversionPattern() const;
Gets the conversion pattern matching string for the Patternlayout object
void setConversionPattern(const QString &rPattern);
Sets the conversion pattern matching string for the Patternlayout object
void setConversionPattern(ConversionPattern conversionPattern);
To set the conversion pattern matching for a Patternlayout object

3. Format formatted implementation
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 according to each mode converter of the schema converter list.

QString PatternFormatter::format(const LoggingEvent &rLoggingEvent) const    {        QString result;        PatternConverter *p_converter;        Q_FOREACH(p_converter, mPatternConverters)            p_converter->format(result, rLoggingEvent);        return result;    }

The

Patternformatter uses a pattern-matching string to create a pattern converter mpatternconverters, each of which corresponds to a schema converter.

    void Patternformatter::createconverter (const Qchar &rchar, const FORMAT Tinginfo &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 << QString (Rchar) << formattinginfo::inttostring (rformattinginfo.mminlength) << for Mattinginfo::inttostring (rformattinginfo.mmaxlength) << rformattinginfo.mleftaligned << RO        ption;        Logger ()->trace (e); Switch (rchar.tolatin1 ()) {case ' C ': mpatternconverters << new Loggerpatternconver    ter (Rformattinginfo, Parseintegeroption (roption));            Break                Case ' d ': {QString option = roption;                if (Roption.isempty ()) option = qlatin1string ("ISO8601");                                                                Mpatternconverters << New Datepatternconverter (Rformattinginfo,                 option);            Break                                                                } case ' m ': mpatternconverters << new Basicpatternconverter (Rformattinginfo,                 Basicpatternconverter::message_converter);            Break                                                                Case ' P ': mpatternconverters << new Basicpatternconverter (Rformattinginfo,                 Basicpatternconverter::level_converter);            Break                                               Case ' R ': Mpatternconverters << new Datepatternconverter (Rformattinginfo,                Qlatin1string ("RELATIVE"));            Break                                                                Case ' t ': mpatternconverters << new Basicpatternconverter (Rformattinginfo,                 Basicpatternconverter::thread_converter);            Break                                                                Case ' x ': mpatternconverters << new Basicpatternconverter (Rformattinginfo,                 Basicpatternconverter::ndc_converter);            Break                                                               Case ' X ': mpatternconverters << new Mdcpatternconverter (Rformattinginfo,                 Roption);            Break        Default:q_assert_x (False, "Patternformatter::createconverter", "Unknown pattern character"); }    }
4. Patternlayout Use Example
#include <QCoreApplication> #include <log4qt/logger.h> #include <log4qt/patternlayout.h> #include    <log4qt/consoleappender.h> #include <log4qt/loggerrepository.h>int main (int argc, char *argv[]) {    Qcoreapplication A (argc, argv);    Get Rootlogger Log4qt::logger *logger = Log4qt::logger::rootlogger ();    Create patternlayout (output log events based on pattern string) LOG4QT::P atternlayout *layout = new LOG4QT::P atternlayout ();    Set Header information Layout->setheader ("-----Start-----");    Set footer information Layout->setfooter ("-----End-----");    Set the conversion Mode Layout->setconversionpattern ("%d{yyyy-mm-dd hh:mm:ss} [%p]-%m%n");    Activate layout layout->activateoptions (); Create Consoleappender Log4qt::consoleappender *appender = new Log4qt::consoleappender (Layout, Log4qt::consoleappender:    : Stdout_target);    Appender->activateoptions ();    Logger->addappender (Appender);    Logger->setlevel (log4qt::level::D ebug_int);    Logger->debug ("Debug, log4qt!"); Logger-> info ("info, log4qt!");    Close logger logger->removeallappenders ();    Logger->loggerrepository ()->shutdown (); return a.exec ();} output://-----Start-----//2018-10-11 21:25:30 [Debug]-DEBUG, log4qt!//2018-10-11 21:25:30 [INFO]-INFO, log4qt! -----End-----
5, Configuration Patternlayout

To configure Patternlayout with the log4qt.properties configuration file:

# 定义 rootLoggerlog4j.rootLogger=DEBUG, console# 定义 ConsoleAppenderlog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.immediateFlush=truelog4j.appender.console.target=STDOUT_TARGET# 为 ConsoleAppender 定义 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 use:

#include <QCoreApplication>#include <log4qt/logger.h>#include <log4qt/loggerrepository.h>#include <QThread>int main(int argc, char *argv[]){    QCoreApplication a(argc, argv);    QThread::currentThread()->setObjectName("MainThread");    // 获取rootLogger    Log4Qt::Logger* logger = Log4Qt::Logger::rootLogger();    // 打印消息    logger->debug("Debug, Log4Qt!");    logger->info("Info, Log4Qt!");    // 关闭rootLogger    logger->removeAllAppenders();    logger->loggerRepository()->shutdown();    return a.exec();}// output:// ----- start -----// 2018-10-11 21:35:58 [MainThread] DEBUG root  - Debug, Log4Qt!// 2018-10-11 21:35:58 [MainThread] INFO root  - Info, Log4Qt!// ----- end -----
Three, SIMPLELAYOUT1, Simplelayout Introduction

Simplelayout is a derived class for layout, and formatting a log message contains only the level of the log and the message content.

2. Format formatted implementation
QString SimpleLayout::format(const LoggingEvent &rEvent)    {        return rEvent.level().toString() + QLatin1String(" - ") + rEvent.message() + Layout::endOfLine();    }

Simplelayout formatting a log message contains only the level of the log and the message content.

3. simplelayout Example
#include <QCoreApplication> #include <log4qt/logger.h> #include <log4qt/simplelayout.h> #include    <log4qt/consoleappender.h> #include <log4qt/loggerrepository.h>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::D ebug_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, log4qt!//end 
4, Configuration Simplelayout

To configure Simplelayout with the log4qt.properties configuration file:

# 定义 rootLoggerlog4j.rootLogger=DEBUG, console# 定义 ConsoleAppenderlog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.immediateFlush=truelog4j.appender.console.target=STDOUT_TARGET# 为 ConsoleAppender 定义 Layoutlog4j.appender.console.layout=org.apache.log4j.SimpleLayoutlog4j.appender.console.layout.header=----- start -----log4j.appender.console.layout.footer=----- end -----

Examples of program use:

#include <QCoreApplication>#include <log4qt/logger.h>#include <log4qt/loggerrepository.h>int main(int argc, char *argv[]){    QCoreApplication a(argc, argv);    // 获取 rootLogger    Log4Qt::Logger* logger = Log4Qt::Logger::rootLogger();    // 打印消息    logger->debug("Hello, Log4Qt!");    logger->info("Hello, Log4Qt!");    // 关闭 rootLogger    logger->removeAllAppenders();    logger->loggerRepository()->shutdown();    return a.exec();}// output:// ----- start -----// DEBUG - Hello, Log4Qt!// INFO - Hello, Log4Qt!// ----- end -----
Iv. Introduction to TTCCLAYOUT1 and Ttcclayout

Ttcclayout is a derived class of layout that is responsible for providing detailed information about log events, usually including the following:
Time: The number of milliseconds from the start of the application;
Thread: the calling thread;
Category: The class or logger used to create log events;
CONTEXT:NDC information. NDC information is not automatically included in the Loggingevent object and must be specifically included in the NDC information. Therefore, the context is an optional output of ttcclayout, and ttcclayout may not display any NDC data if the loggingevent does not contain any NDC settings, even if NDC settings are enabled.
? Ttcclayout has multiple optional parameters, but even if you don't set any options,? Ttcclayout will still output the following information:
Level: Levels of log messages;
Message: The log message itself.
Ttcclayout has predefined multiple date formats, defined as follows:

enum DateFormat{    NONE,//没有日期格式    ISO8601,// yyyy-MM-dd hh:mm:ss.zzz    ABSOLUTE,// HH:mm:ss.zzz    DATE,//MMM YYYY HH:mm:ss.zzzz    RELATIVE // 程序启动开始的毫秒数量};
2, Ttcclayout Common interface

bool categoryPrefixing() const;
Gets whether the output logger name is formatted
bool contextPrinting() const;
Gets whether to format the output of NDC information
QString dateFormat() const;
Get a string of date format
bool threadPrinting() const;
Gets whether the output thread name is formatted
void setCategoryPrefixing(bool categoryPrefixing);
Sets whether the specified logger name is a formatted output.
void setContextPrinting(bool contextPrinting);
Set whether to format the output of NDC information
void setDateFormat(const QString &rDateFormat);
Sets the date format for the Rdateformat string representation
void setDateFormat(DateFormat dateFormat);
Set 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);
Press Rmessage information into the NDC stack
static QString Log4Qt::NDC::pop();
To stack top information from the NDC stack

3. Format formatted implementation
QString TTCCLayout::format(const LoggingEvent &rEvent){    Q_ASSERT_X(mpPatternFormatter, "TTCCLayout::format()", "mpPatternConverter must not be null");    return mpPatternFormatter->format(rEvent);}

The format of the ttcclayout is the same as the format method of Patternlayout, which is the format information for each pattern converter linked list created from the pattern-matching string.

4. ttcclayout Example
#include <QCoreApplication> #include <log4qt/logger.h> #include <log4qt/ttcclayout.h> #include < log4qt/consoleappender.h> #include <log4qt/loggerrepository.h> #include <log4qt/ndc.h> #include <    Qthread>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::D ebug_int);    NDC information LOG4QT::NDC::p ush ("Thread start");    Logger->debug ("Hello, log4qt!");    LOG4QT::NDC::p op (); 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, log4qt!//2018-18-11 23:18:12 [MainThread] INFO Root-hello, log4qt!
5, Configuration Ttcclayout

To configure Ttcclayout with the log4qt.properties configuration file:

# 定义rootLoggerlog4j.rootLogger=DEBUG, console# 定义ConsoleAppenderlog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.immediateFlush=truelog4j.appender.console.target=STDOUT_TARGET# 为ConsoleAppender定义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

Examples of program use:

#include <QCoreApplication>#include <log4qt/logger.h>#include <log4qt/ttcclayout.h>#include <log4qt/consoleappender.h>#include <log4qt/loggerrepository.h>#include <log4qt/ndc.h>#include <QThread>int main(int argc, char *argv[]){    QCoreApplication a(argc, argv);    QThread::currentThread()->setObjectName("MainThread");    Log4Qt::Logger *logger = Log4Qt::Logger::rootLogger();    // NDC信息    Log4Qt::NDC::push("Thread start");    logger->debug("Hello, Log4Qt!");    Log4Qt::NDC::pop();    logger->info("Hello, Log4Qt!");    // 关闭 logger    logger->removeAllAppenders();    logger->loggerRepository()->shutdown();    return a.exec();}// output:// 2018-10-11 23:22:09.936 [MainThread] DEBUG root Thread start - Hello, Log4Qt!// 2018-10-11 23:22:09.936 [MainThread] INFO  root  - Hello, Log4Qt!

LOG4QT Quick Start--LOG4QT log format source parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.