Jump to content
phreak

[C++] Logger

Recommended Posts

Posted

Exemplu de folosire :


xLogger logger;
logger.addFile("first.txt",std::ios::app);
logger.addFile("second.txt",std::ios::out);

logger<<"first post";
logger<<"abcdef";
logger<<"123";
logger<<"456";

Output ( in cout si amandoua fisierele ) :


##################################################
[2011-Sep-05 15:17:40] first post
[2011-Sep-05 15:17:40] abcdef
[2011-Sep-05 15:17:40] 123
[2011-Sep-05 15:17:40] 456

Sursa : http://codepad.org/eqzorpcV


#ifndef XLOGGER_H
#define XLOGGER_H

#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/date_time.hpp>
#include <fstream>
#include <iostream>

class TempLogger : public boost::enable_shared_from_this<TempLogger>
{
public:
TempLogger(std::vector<std::ofstream *> & streams): m_Streams(streams) {}

template<typename T>
boost::shared_ptr<TempLogger> operator<<(const T & value)
{
for(int i = 0 ; i < m_Streams.size(); i++)
*m_Streams.at(i)<<value;

std::cout<<value;

return shared_from_this();
}

~TempLogger()
{
for(int i = 0 ; i < m_Streams.size(); i++)
*m_Streams.at(i)<<std::endl;

std::cout<<std::endl;
}

private:
std::vector<std::ofstream *> & m_Streams;
};

template <typename T>
boost::shared_ptr<TempLogger> operator<<(boost::shared_ptr<TempLogger> logger, T const & t)
{
return (*logger) << t;
}

struct xLogger {
xLogger() {}

void addFile(std::string filename,std::ios_base::openmode openMode)
{
m_Streams.push_back(new std::ofstream(filename.c_str(),openMode));
*m_Streams.back()<<"##################################################"<<std::endl;
}

template<typename T>
boost::shared_ptr<TempLogger> operator<<( const T & value){

boost::shared_ptr<TempLogger> temp(new TempLogger(m_Streams));

for(int i = 0 ; i < m_Streams.size() ; i++)
*m_Streams.at(i)<<"[" + to_simple_string(boost::posix_time::second_clock::local_time()) + "] "<<value;

std::cout<<"[" + to_simple_string(boost::posix_time::second_clock::local_time()) + "] "<<value;

return temp;
}

~xLogger()
{
for(int i = 0 ; i < m_Streams.size() ; i++)
{
m_Streams.at(i)->close();
delete m_Streams.at(i);
}
}

private:
std::vector<std::ofstream *> m_Streams;
};

#endif // XLOGGER_H

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...