Create your own Log format with log4cpp::PatternLayout

Posted by Joys of Programming on in C/C++

log4cpp::PatternLayout supports four different patterns of log format. But it also supports user specified format. For this purpose, it gives certain format chracters. Some of them are

  • %d: Date
  • %m: log message
  • %n: line separator
  • %p: priority

For more such characters refer PatternLayout.

The additional benefit of using a format of your own is that you can specify some additional information like application name without explicitly adding to all the log messages or additinal separators like :, ;, -

The following program sets a conversionPattern %d: %p – %m %n. This corresponds to the log message consisting of the date, followed by a colon, priority followed by a hyphen and then the message ending with a newline character

The function setConversionPattern is used.

void log4cpp::PatternLayout::setConversionPattern(const std::string & conversionPattern)

Check the following program

#include <stdio.h>
#include <stdlib.h>
#include <log4cpp/category.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/PatternLayout.hh>

using namespace std;

int main()
{
 /*Setting up Appender, <span id="IL_AD4">layout</span> and Category*/
 log4cpp::Appender *appender = new log4cpp::OstreamAppender("OstreamAppender",&cout);

 log4cpp::PatternLayout *layout = new log4cpp::PatternLayout();
 layout->setConversionPattern("%d: %p - %m %n");
 log4cpp::Category& category = log4cpp::Category::getInstance("Category");

 appender->setLayout(layout);
 category.setAppender(appender);
 category.setPriority(log4cpp::Priority::INFO);

 category.info("This is for tracing the flow");
 category.notice("This is to notify certain events");
 category.warn("This is to generate certain warnings");
 category.error("This is to generate errors");
}

The output of the program as seen on the terminal


2010-01-14 14:47:43,104: INFO - This is for tracing the flow
2010-01-14 14:47:43,104: NOTICE - This is to notify certain events
2010-01-14 14:47:43,104: WARN - This is to generate certain warnings
2010-01-14 14:47:43,105: ERROR - This is to generate errors

Now try to create  a format of your own.

Reblog this post [with Zemanta]


Tags: , , , , , , ,

Comments:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2009-2012 Joys of Programming All rights reserved.
Desk Mess Mirrored v1.8.1 theme from BuyNowShop.com.