2019-04-16 13:20:48 +00:00
|
|
|
#include <util/file_logger.hpp>
|
|
|
|
#include <util/logger_internal.hpp>
|
|
|
|
|
|
|
|
namespace llarp
|
|
|
|
{
|
2019-05-18 18:46:49 +00:00
|
|
|
namespace
|
|
|
|
{
|
|
|
|
static void
|
2019-06-13 13:26:34 +00:00
|
|
|
Flush(std::deque< std::string > lines, FILE *const f)
|
2019-05-18 18:46:49 +00:00
|
|
|
{
|
|
|
|
for(const auto &line : lines)
|
|
|
|
fprintf(f, "%s\n", line.c_str());
|
|
|
|
fflush(f);
|
|
|
|
}
|
|
|
|
} // namespace
|
|
|
|
FileLogStream::FileLogStream(thread::ThreadPool *disk, FILE *f,
|
2019-06-13 13:26:34 +00:00
|
|
|
llarp_time_t flushInterval, bool closeFile)
|
|
|
|
: m_Disk(disk)
|
|
|
|
, m_File(f)
|
|
|
|
, m_FlushInterval(flushInterval)
|
|
|
|
, m_Close(closeFile)
|
2019-04-16 13:20:48 +00:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
FileLogStream::~FileLogStream()
|
|
|
|
{
|
|
|
|
fflush(m_File);
|
2019-06-13 13:26:34 +00:00
|
|
|
if(m_Close)
|
|
|
|
fclose(m_File);
|
2019-04-16 13:20:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
bool
|
|
|
|
FileLogStream::ShouldFlush(llarp_time_t now) const
|
|
|
|
{
|
|
|
|
if(m_LastFlush >= now)
|
|
|
|
return false;
|
|
|
|
const auto dlt = now - m_LastFlush;
|
|
|
|
return dlt >= m_FlushInterval;
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
FileLogStream::PreLog(std::stringstream &ss, LogLevel lvl, const char *fname,
|
2019-06-13 13:26:34 +00:00
|
|
|
int lineno, const std::string &nodename) const
|
2019-04-16 13:20:48 +00:00
|
|
|
{
|
2019-06-13 13:26:34 +00:00
|
|
|
ss << "[" << LogLevelToString(lvl) << "] ";
|
|
|
|
ss << "[" << nodename << "]"
|
|
|
|
<< "(" << thread_id_string() << ") " << log_timestamp() << " " << fname
|
2019-04-16 13:20:48 +00:00
|
|
|
<< ":" << lineno << "\t";
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
FileLogStream::Print(LogLevel, const char *, const std::string &msg)
|
|
|
|
{
|
|
|
|
m_Lines.emplace_back(msg);
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
FileLogStream::Tick(llarp_time_t now)
|
|
|
|
{
|
|
|
|
if(ShouldFlush(now))
|
|
|
|
FlushLinesToDisk(now);
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
FileLogStream::FlushLinesToDisk(llarp_time_t now)
|
|
|
|
{
|
2019-06-13 13:26:34 +00:00
|
|
|
FILE *const f = m_File;
|
|
|
|
std::deque< std::string > lines(m_Lines);
|
|
|
|
m_Disk->addJob([=]() { Flush(lines, f); });
|
|
|
|
m_Lines.clear();
|
2019-04-16 13:20:48 +00:00
|
|
|
m_LastFlush = now;
|
|
|
|
}
|
2019-05-18 18:46:49 +00:00
|
|
|
} // namespace llarp
|