OstreamAppender: Direct the log4cpp logs to standard Output
log4cpp enables you to easily log important events. The logs can be directed to files or even periodically rolled back and back up. There are multiple destinations for the log files and you can decide which one to choose from. Though in most cases, you want to use log files, you can also make use of the standard output i.e., the logs can be displayed on the terminal or command prompt.
To direct the logs to standard output, you must use log4cpp::OstreamAppender class. The following program depicts this
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <log4cpp/Category.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/SimpleLayout.hh>
using namespace std;
int main()
{
/*Setting up Appender, layout and Category*/
log4cpp::Appender *appender = new log4cpp::OstreamAppender("OstreamAppender",&cout);
log4cpp::Layout *layout = new log4cpp::SimpleLayout();
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");
}
Here the important portion is the snippet
log4cpp::Appender *appender = new log4cpp::OstreamAppender("OstreamAppender",&cout);
The syntax of OstreamAppender is as follows
OstreamAppender(const std::string &name, std::ostream *stream)
where name corresponds to any name you want to give your Appender. I have used the name “OstreamAppender”. The second argument corresponds to a stream. As you can see in the snippet, the standard output which is usually referred in C++ as cout is passed as a parameter. On running this program, we get the logs on the terminal
./OstreamAppender INFO : This is for tracing the flow NOTICE : This is to notify certain events WARN : This is to generate certain warnings
OstreamAppender can be very useful if you want to debug your program using logs.
Comments: