//
// Copyright (c) 2009-2010 Ronald Kluth
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

/**
 * @file Example_Channel_Consumer.cpp
 * @author Ronald Kluth
 * @date 2009/11/22
 * @brief Example introducing basic channel and consumer usage
 * @since 0.1
 */

/**
 * @example Example_Channel_Consumer.cpp
 * 
 * This example introduces basic channel usage with a custom consumer class.
 * The consumer class @c %ConsoleWriter simply disregards the channel ID and
 * prints the record string to the console.
 * 
 * The main function shows the use of a channel object and a @c shared_ptr 
 * -managed channel using @c std::string as record type. First, a consumer
 * is created, which is registered to a channel object. The following log
 * record is then printed to the console.
 * 
 * Wrapping the channel in a
 * @c shared_ptr provides a few more options. When the pointer is set, the
 * record is forwarded to the console as expected. However, resetting the
 * pointer disables logging through that channel because the pointer is checked
 * in @c operator<<. However, the call to the operator still requires the
 * record object to be created. This overhead can also be avoided by checking
 * the pointer before even making the logging call, as is shown in the last 
 * statement.
 */

#include <CppLog.h>
#include <iostream>

typedef std::string Rec;

class ConsoleWriter: public Log::Consumer< Rec > {
public:
	virtual void consume( const Log::ChannelId channelId, const Rec& record ) {
		std::cout << record << std::flush;
	}
};

int main() {
	typedef std::tr1::shared_ptr< Log::Channel< Rec > > ChannelPtr;
	typedef std::tr1::shared_ptr< Log::Consumer< Rec > > ConsumerPtr;
	ConsumerPtr consoleWriter = ConsumerPtr( new ConsoleWriter() );

	Log::Channel< Rec > channel;
	channel.addConsumer( consoleWriter );
	channel << Rec( "Logging via Channel object\n" );

	ChannelPtr p_channel( new Log::Channel< Rec >() );
	p_channel->addConsumer( consoleWriter );
	p_channel << Rec( "Logging via set Channel pointer produces output\n" );
	p_channel.reset();
	p_channel << Rec( "Logging via empty pointer prints nothing\n" );
	if( p_channel )
		p_channel << Rec( "Checking empty pointer avoids record creation\n" );
}
