i2pd/Log.h

90 lines
1.5 KiB
C
Raw Normal View History

2013-12-10 13:00:13 +00:00
#ifndef LOG_H__
#define LOG_H__
2014-04-24 15:10:46 +00:00
#include <string>
2013-12-10 13:00:13 +00:00
#include <iostream>
#include <sstream>
2014-04-24 15:10:46 +00:00
#include <fstream>
2014-04-23 16:49:02 +00:00
#include <functional>
2013-12-10 13:00:13 +00: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 13:00:13 +00:00
};
2014-04-23 16:49:02 +00:00
class Log: public i2p::util::MsgQueue<LogMsg>
{
public:
2014-04-24 15:10:46 +00: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 16:49:02 +00:00
private:
void Flush ();
2014-04-24 15:10:46 +00:00
private:
std::ofstream * m_LogFile;
2014-04-23 16:49:02 +00:00
};
2014-07-02 17:48:45 +00:00
extern Log * g_Log;
inline void StartLog (const std::string& fullFilePath)
{
if (!g_Log)
{
g_Log = new Log ();
2014-07-02 18:25:57 +00:00
if (fullFilePath.length () > 0)
g_Log->SetLogFile (fullFilePath);
2014-07-02 17:48:45 +00:00
}
}
inline void StopLog ()
{
if (g_Log)
{
delete g_Log;
g_Log = nullptr;
}
}
2013-12-10 13:00:13 +00: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 17:48:45 +00:00
LogMsg * msg = (g_Log && g_Log->GetLogFile ()) ? new LogMsg (*g_Log->GetLogFile ()) : new LogMsg ();
2013-12-10 13:00:13 +00:00
LogPrint (msg->s, args...);
msg->s << std::endl;
2014-07-02 17:48:45 +00:00
if (g_Log)
g_Log->Put (msg);
else
{
msg->Process ();
delete msg;
}
2013-12-10 13:00:13 +00:00
}
#endif