i2pd/Log.h

118 lines
1.9 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"
2014-10-28 20:36:17 +00:00
enum LogLevel
{
eLogError = 0,
eLogWarning,
eLogInfo,
eLogDebug,
eNumLogLevels
};
2013-12-10 13:00:13 +00:00
struct LogMsg
{
std::stringstream s;
std::ostream& output;
2014-10-28 20:36:17 +00:00
LogLevel level;
2013-12-10 13:00:13 +00:00
2014-10-28 20:36:17 +00:00
LogMsg (std::ostream& o = std::cout, LogLevel l = eLogInfo): output (o), level (l) {};
2013-12-10 13:00:13 +00:00
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:
Log (): m_LogStream (nullptr) { SetOnEmpty (std::bind (&Log::Flush, this)); };
~Log () { delete m_LogStream; };
2014-04-24 15:10:46 +00:00
void SetLogFile (const std::string& fullFilePath);
void SetLogStream (std::ostream * logStream);
std::ostream * GetLogStream () const { return m_LogStream; };
2014-04-23 16:49:02 +00:00
private:
void Flush ();
2014-04-24 15:10:46 +00:00
private:
std::ostream * m_LogStream;
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 StartLog (std::ostream * s)
{
if (!g_Log)
{
g_Log = new Log ();
if (s)
g_Log->SetLogStream (s);
}
}
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>
2014-10-28 20:36:17 +00:00
void LogPrint (LogLevel level, TArgs... args)
2013-12-10 13:00:13 +00:00
{
LogMsg * msg = (g_Log && g_Log->GetLogStream ()) ? new LogMsg (*g_Log->GetLogStream (), level) :
2014-10-28 20:36:17 +00:00
new LogMsg (std::cout, level);
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;
}
2014-10-28 20:36:17 +00:00
}
template<typename... TArgs>
void LogPrint (TArgs... args)
{
LogPrint (eLogInfo, args...);
2013-12-10 13:00:13 +00:00
}
#endif