Log4cplus Study Notes (2)

Source: Internet
Author: User

Log4cplus is excellent in many aspects, but it is uncomfortable to use it in some places. I'm not happy with it until I continue to talk about it.
I will mention it a little and continue to introduce the knowledge about threads and sockets.
### Some improvements ###
1. The implementation mechanism of user-defined loglevel is not open enough
In article 5, I have introduced how to implement custom loglevel. To achieve better results, I even need to change log4cplus.
Source code. :(
2. The mechanism for generating logger objects can be improved.
When using logger, I often need to operate the same logger in different files and functions. Although log4cplus implements tree storage and
The logger generated by the name does not take full advantage of this feature to ensure the uniqueness of the logger object corresponding to the same name. For example, the following code:
......

Logger logger1 = logger: getinstance ("test ");
Logger logger2 = logger: getinstance ("test ");
Logger * plogger1 = & logger1;
Logger * plogger2 = & logger2;
STD: cout <"plogger1:" <plogger1 <STD: Endl <"plogger2:" <plogger2 <STD: Endl;

......

Running result:
Plogger1: 0xbfffe5a0
Plogger2: 0xbfffe580

It can be seen from the results that it is clearly the same logger, but each call will generate a logger copy, although the result is correct (because
The storage and operations are separated), but the resources are a little waste. I checked the log4cplus code and can actually be implemented as follows (schematic
):
# Include <iostream> </iostream>
# Include <string> </string>
# Include
/* Forward Declaration */
Class logger;
Class loggercontainer
{
Public:
~ Loggercontainer ();
Logger * getinstance (const STD: string & strlogger );
PRIVATE:
Typedef STD: Map <: String,> loggermap;
Loggermap loggerptrs;
};
Class Logger
{
Public:
Logger () {STD: cout <"ctor of logger" <STD: Endl ;}
~ Logger () {STD: cout <"dtor of logger" <STD: Endl ;}
Static logger * getinstance (const STD: string & strlogger)
{
Static loggercontainer defaultloggercontainer;
Return defaultloggercontainer. getinstance (strlogger );
}
};
Loggercontainer ::~ Loggercontainer ()
{
/* Release all PTR in loggermap */
Loggermap: iterator itr = loggerptrs. Begin ();
For (; itr! = Loggerptrs. End (); ++ itr)
{
Delete (* itr). Second;
}
}
Logger * loggercontainer: getinstance (const STD: string & strlogger)
{
Loggermap: iterator itr = loggerptrs. Find (strlogger );
If (itr! = Loggerptrs. End ())
{
/* Logger exist, just return it */
Return (* itr). Second;
}
Else
{
/* Return a new logger */
Logger * plogger = new logger ();
Loggerptrs. insert (STD: make_pair (strlogger, plogger ));
Return plogger;
}
}
Int main ()
{
Logger * plogger1 = logger: getinstance ("test ");
Logger * plogger2 = logger: getinstance ("test ");
STD: cout <"plogger1:" <plogger1 <STD: Endl <"plogger2:" <plogger2 <STD: Endl;
Return 0;
}

Running result:
Ctor of logger
Plogger1: 0x804fc30
Plogger2: 0x804fc30
Dtor of logger
The loggercontainer here is equivalent to the hierarchy class in log4cplus. The result shows that the same name can be used to obtain the same
Logger instance.

There are also some minor issues, such as the parameter input sequence of rollingfileappender and dailyrollingfileappender, which can be adjusted to the unified mode.
Wait.
This section describes how log4cplus processes and sockets are implemented.

(7)

After a short familiarization process, log4cplus has been successfully applied to my project, and the effect is good. :) besides
In addition to the function, the following describes the usage of threads and sockets provided by log4cplus.
### NDC ###
First, let's take a look at the embedded diagnostic context (nested diagnostic context) in log4cplus, that is, NDC. For the log system,
When there may be more than one input source, but only one output, it is often necessary to distinguish the source of the message to be output, such as the server processing from different
This judgment is required when the client sends messages. NDC can mark (STAMP) the information displayed in the staggered manner to make the identification work look like
It's easier. This mark is unique to the thread and uses the local storage mechanism of the thread.
Data, or TSD ). After reading the source code, the definition is as follows:
Linux pthread
# Define log4cplus_thread_local_type pthread_key_t *
# Define log4cplus_thread_local_init: log4cplus: thread: createpthreadkey ()
# Define log4cplus_get_thread_local_value (key) pthread_getspecific (* key)
# Define log4cplus_set_thread_local_value (Key, value) pthread_setspecific (* Key, value)
# Define log4cplus_thread_local_cleanup (key) pthread_key_delete (* key)
Win32
# Define log4cplus_thread_local_type DWORD
# Define log4cplus_thread_local_init tlsalloc ()
# Define log4cplus_get_thread_local_value (key) tlsgetvalue (key)
# Define log4cplus_set_thread_local_value (Key, value )\
Tlssetvalue (Key, static_cast <lpvoid> </lpvoid> (value ))
# Define log4cplus_thread_local_cleanup (key) tlsfree (key)

It is relatively simple to use. In a thread:
NDC & NDC = log4cplus: getndc ();
NDC. Push ("ur NDC string ");
Log4cplus_debug (logger, "This is a NDC test ");
......

NDC. Pop ();

......

Log4cplus_debug (logger, "There shocould be no NDC ...");
NDC. Remove ();

When the output format (layout) is set to ttcclayout, the output is as follows:
10-21-04 21:32:58, [3392] Debug test <ur string = "" NDC = ""> </UR>-this is a NDC Test
10-21-04 21:32:58, [3392] Debug test <>-There shocould be no NDC...
You can also use NDC (% x) in the Custom output format, for example:
......

STD: String Pattern = "NDC: [% x]-% m % N ";
STD: auto_ptr <layout> </layout> _ layout (New patternlayout (pattern ));
......

Log4cplus_debug (_ logger, "This is the first log message ...")
NDC & NDC = log4cplus: getndc ();
NDC. Push ("ur NDC string ");
Log4cplus_warn (_ logger, "this is the second log message ...")
NDC. Pop ();
NDC. Remove ();

......

The output is as follows:
NDC: []-This is the first log message...
NDC: [Ur NDC string]-This is the second log message...

Another simpler method is to directly use ndccontextcreator in the thread:
Ndccontextcreator _ first_ndc ("ur NDC string ");
Log4cplus_debug (logger, "This is a NDC test ")

You do not need to explicitly call push/pop. In case of an exception, you can ensure that the call of push and pop matches.

### Thread ###
The thread is a by-product in log4cplus and only implements the most basic functions. It is also very simple to use.
Reload the run function in the derived class:
Class testthread: Public abstractthread
{
Public:
Virtual void run ();
};
Void testthread: Run ()
{
/* Do Something .*/
......
}
The log4cplus thread does not consider synchronization or deadlocks and has mutex. The small functions that implement thread switching are quite chic:
Void log4cplus: thread: yield ()
{
# If defined (log4cplus_use_pthreads)
: Sched_yield ();
# Elif defined (log4cplus_use_win32_threads)
: Sleep (0 );
# Endif
}

### Socket ###
Sockets are also a by-product in log4cplus. In namespace log4cplus: helpers, logs are recorded in C/S mode.
1. What the client needs to do:
/* Define a etappender hook */
Sharedappenderptr _ append (New socketappender (host, 8888, "servername "));
/* Add _ append to logger */
Logger: getroot (). addappender (_ append );
/* The socketappender type does not require layout. You can directly call the macro to send the information to loggerserver */
Log4cplus_info (logger: getroot (), "this is a test :")

[Note] the macro call actually calls socketappender: append, which has a data transmission Convention, that is, sending
The total length of a subsequent data, and then the actual data is sent:
......
Socketbuffer buffer = converttobuffer (event, servername );
Socketbuffer msgbuffer (log4cplus_max_message_size );
Msgbuffer. appendsize_t (buffer. getsize ());
Msgbuffer. appendbuffer (buffer );

......

2. What the server-side program needs to do:
/* Define a serversocket */
Serversocket (port );
/* Call the accept function to create a new socket to connect to the client */
Socket sock = serversocket. Accept ();

Then you can use the sock for data read/write, as shown in the following figure:
Socketbuffer msgsizebuffer (sizeof (unsigned INT ));
If (! Clientsock. Read (msgsizebuffer ))
{
Return;
}
Unsigned int msgsize = msgsizebuffer. readint ();
Socketbuffer buffer (msgsize );
If (! Clientsock. Read (buffer ))
{
Return;
}
To display the read data normally, you need to convert the contents stored in socketbuffer to internalloggingevent format:
SPI: internalloggingevent event = readfrombuffer (buffer );
Then output:
Logger logger = logger: getinstance (event. getloggername ());
Logger. callappenders (event );
[Note] read/write is implemented in blocking mode, which means that the call will not be returned until the number of received or sent messages is satisfied.

Three log4cplus routines

Http://log4cplus.sourceforge.net/codeexamples.html

Three built-in routines

Hello world example

#include <log4cplus/logger.h> #include <log4cplus/configurator.h> #include <iomanip>using namespace log4cplus;int main() {     BasicConfigurator config;     config.configure();     Logger logger = Logger::getInstance("main");     LOG4CPLUS_WARN(logger, "Hello, World!");     return 0; }

Ostream example (show how to write logging messages .)

#include <log4cplus/logger.h>#include <log4cplus/configurator.h>#include <iomanip>using namespace std;using namespace log4cplus;intmain(){    BasicConfigurator config;    config.configure();    Logger logger = Logger::getInstance("logger");    LOG4CPLUS_WARN(logger,   "This is"                           << " a reall"                           << "y long message." << endl                           << "Just testing it out" << endl                           << "What do you think?")    LOG4CPLUS_WARN(logger, "This is a bool: " << true)    LOG4CPLUS_WARN(logger, "This is a char: " << 'x')    LOG4CPLUS_WARN(logger, "This is a short: " << (short)-100)    LOG4CPLUS_WARN(logger, "This is a unsigned short: " << (unsigned short)100)    LOG4CPLUS_WARN(logger, "This is a int: " << (int)1000)    LOG4CPLUS_WARN(logger, "This is a unsigned int: " << (unsigned int)1000)    LOG4CPLUS_WARN(logger, "This is a long(hex): " << hex << (long)100000000)    LOG4CPLUS_WARN(logger, "This is a unsigned long: "                    << (unsigned long)100000000)    LOG4CPLUS_WARN(logger, "This is a float: " << (float)1.2345)    LOG4CPLUS_WARN(logger, "This is a double: "                           << setprecision(15)                           << (double)1.2345234234)    LOG4CPLUS_WARN(logger, "This is a long double: "                           << setprecision(15)                           << (long double)123452342342.342)    return 0;}

Loglevel example (shows how log messages can be filtered at runtime by adjusting the loglevel .)

#include <log4cplus/logger.h>#include <log4cplus/configurator.h>#include <iostream>using namespace std;using namespace log4cplus;Logger logger = Logger::getInstance("main");void printMessages(){    LOG4CPLUS_TRACE(logger, "printMessages()");    LOG4CPLUS_DEBUG(logger, "This is a DEBUG message");    LOG4CPLUS_INFO(logger, "This is a INFO message");    LOG4CPLUS_WARN(logger, "This is a WARN message");    LOG4CPLUS_ERROR(logger, "This is a ERROR message");    LOG4CPLUS_FATAL(logger, "This is a FATAL message");}intmain(){    BasicConfigurator config;    config.configure();    logger.setLogLevel(TRACE_LOG_LEVEL);    cout << "*** calling printMessages() with TRACE set: ***" << endl;    printMessages();    logger.setLogLevel(DEBUG_LOG_LEVEL);    cout << "\n*** calling printMessages() with DEBUG set: ***" << endl;    printMessages();    logger.setLogLevel(INFO_LOG_LEVEL);    cout << "\n*** calling printMessages() with INFO set: ***" << endl;    printMessages();    logger.setLogLevel(WARN_LOG_LEVEL);    cout << "\n*** calling printMessages() with WARN set: ***" << endl;    printMessages();    logger.setLogLevel(ERROR_LOG_LEVEL);    cout << "\n*** calling printMessages() with ERROR set: ***" << endl;    printMessages();    logger.setLogLevel(FATAL_LOG_LEVEL);    cout << "\n*** calling printMessages() with FATAL set: ***" << endl;    printMessages();    return 0;}

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.