Open-source log system-log4cplus (7)

Source: Internet
Author: User

 

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(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  - this is a NDC test
10-21-04 21:32:58, [3392] DEBUG test <> - There should 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(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 sth. */
    ... ...
}
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.

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.