i2pd/Log.h

90 lines
1.5 KiB
C
Raw Normal View History

2013-12-10 17:00:13 +04:00
#ifndef LOG_H__
#define LOG_H__
2014-04-24 19:10:46 +04:00
#include <string>
2013-12-10 17:00:13 +04:00
#include <iostream>
#include <sstream>
2014-04-24 19:10:46 +04:00
#include <fstream>
2014-04-23 20:49:02 +04:00
#include <functional>
2013-12-10 17:00:13 +04:00
#include "Queue.h"
struct LogMsg
{
std::stringstream s;
std::ostream& output;
LogMsg (std::ostream& o = std::cout): output (o) {};
void Process();
2013-12-10 17:00:13 +04:00
};
2014-04-23 20:49:02 +04:00
class Log: public i2p::util::MsgQueue<LogMsg>
{
public:
2014-04-24 19:10:46 +04:00
Log (): m_LogFile (nullptr) { SetOnEmpty (std::bind (&Log::Flush, this)); };
~Log () { delete m_LogFile; };
void SetLogFile (const std::string& fullFilePath);
std::ofstream * GetLogFile () const { return m_LogFile; };
2014-04-23 20:49:02 +04:00
private:
void Flush ();
2014-04-24 19:10:46 +04:00
private:
std::ofstream * m_LogFile;
2014-04-23 20:49:02 +04:00
};
2014-07-02 21:48:45 +04:00
extern Log * g_Log;
inline void StartLog (const std::string& fullFilePath)
{
if (!g_Log)
{
g_Log = new Log ();
2014-07-02 22:25:57 +04:00
if (fullFilePath.length () > 0)
g_Log->SetLogFile (fullFilePath);
2014-07-02 21:48:45 +04:00
}
}
inline void StopLog ()
{
if (g_Log)
{
delete g_Log;
g_Log = nullptr;
}
}
2013-12-10 17:00:13 +04:00
template<typename TValue>
void LogPrint (std::stringstream& s, TValue arg)
{
s << arg;
}
template<typename TValue, typename... TArgs>
void LogPrint (std::stringstream& s, TValue arg, TArgs... args)
{
LogPrint (s, arg);
LogPrint (s, args...);
}
template<typename... TArgs>
void LogPrint (TArgs... args)
{
2014-07-02 21:48:45 +04:00
LogMsg * msg = (g_Log && g_Log->GetLogFile ()) ? new LogMsg (*g_Log->GetLogFile ()) : new LogMsg ();
2013-12-10 17:00:13 +04:00
LogPrint (msg->s, args...);
msg->s << std::endl;
2014-07-02 21:48:45 +04:00
if (g_Log)
g_Log->Put (msg);
else
{
msg->Process ();
delete msg;
}
2013-12-10 17:00:13 +04:00
}
#endif