libcruft-util/log.cpp

286 lines
7.2 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2012-2016 Danny Robson <danny@nerdcruft.net>
*/
#include "log.hpp"
#include "term.hpp"
#include "time.hpp"
#include "cast.hpp"
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
///////////////////////////////////////////////////////////////////////////////
static
const cruft::level_t
ALL_LEVELS[] = {
cruft::EMERGENCY,
cruft::ALERT,
cruft::CRITICAL,
cruft::ERROR,
cruft::WARN,
cruft::NOTICE,
cruft::INFO,
cruft::DEBUG,
};
///////////////////////////////////////////////////////////////////////////////
/// convert a string representation of a log-level into an enumeration value.
///
/// conversion is case insensitive
/// throws std::range_error if unable to convert
static cruft::level_t
to_level (std::string name)
{
if (std::empty (name))
return cruft::EMERGENCY;
static const std::map<std::string, cruft::level_t> NAME_LEVELS = {
{ "EMERGENCY", cruft::EMERGENCY },
{ "ALERT", cruft::ALERT },
{ "CRITICAL", cruft::CRITICAL },
{ "ERROR", cruft::ERROR },
{ "WARN", cruft::WARN },
{ "WARNING", cruft::WARN },
{ "NOTICE", cruft::NOTICE },
{ "INFO", cruft::INFO },
{ "INFORMATIONAL", cruft::INFO },
{ "DEBUG", cruft::DEBUG }
};
std::transform (name.cbegin (), name.cend (), name.begin (), ::toupper);
auto pos = NAME_LEVELS.find (name);
if (pos == NAME_LEVELS.end ())
throw std::range_error (name);
return pos->second;
}
///////////////////////////////////////////////////////////////////////////////
const std::string&
cruft::to_string (level_t l)
{
switch (l) {
#define CASE(L) \
case cruft::L: { \
static const std::string STR = #L; \
return STR; \
}
MAP_LEVEL_T(CASE)
#undef CASE
}
unreachable ();
}
//-----------------------------------------------------------------------------
std::ostream&
cruft::operator<< (std::ostream& os, cruft::level_t l)
{
return os << to_string (l);
}
///////////////////////////////////////////////////////////////////////////////
// Determine what the value for LOG_LEVEL should be at the beginning of
// execution given the system environment.
//
// Note that the LOG macros _cannot_ be used from within this function as it
// will likely result in infinite recursion.
static
cruft::level_t
initial_log_level (void)
{
const char *env = getenv ("LOG_LEVEL");
if (!env)
return cruft::DEFAULT_LOG_LEVEL;
try {
return to_level (env);
} catch (...) {
std::clog << "Invalid environment LOG_LEVEL: '" << env << "'\n";
return cruft::DEFAULT_LOG_LEVEL;
}
}
//-----------------------------------------------------------------------------
// We shouldn't ever actually get to use the default value, but we set it to
// the most verbose option just in case we've made a mistake elsewhere.
static bool s_log_level_done;
static cruft::level_t s_log_level_value;
//-----------------------------------------------------------------------------
cruft::level_t
cruft::log_level (level_t _level)
{
s_log_level_value = _level;
s_log_level_done = true;
return s_log_level_value;
}
//-----------------------------------------------------------------------------
cruft::level_t
cruft::log_level (void)
{
if (!s_log_level_done) {
s_log_level_value = initial_log_level ();
s_log_level_done = true;
}
return s_log_level_value;
}
//-----------------------------------------------------------------------------
static bool
needs_break (cruft::level_t level)
{
static cruft::level_t break_level;
static bool has_level = [&] (void) {
const char *env = getenv ("BREAK_LEVEL");
if (!env)
return false;
try {
break_level = to_level (env);
return true;
} catch (...) {
return false;
}
} ();
return has_level && level <= break_level;
}
//-----------------------------------------------------------------------------
static
cruft::term::csi::graphics
level_colour (cruft::level_t level)
{
using cruft::term::csi::graphics;
switch (level) {
case cruft::EMERGENCY:
case cruft::ALERT:
case cruft::CRITICAL:
case cruft::ERROR:
return graphics (graphics::FOREGROUND, graphics::RED);
case cruft::WARNING:
return graphics (graphics::FOREGROUND, graphics::YELLOW);
case cruft::NOTICE:
case cruft::INFORMATIONAL:
return graphics (graphics::FOREGROUND, graphics::GREEN);
case cruft::DEBUG:
return graphics (graphics::FOREGROUND, graphics::WHITE);
}
unreachable ();
}
//-----------------------------------------------------------------------------
static
size_t
level_width (void)
{
static size_t width = [] {
size_t hi = 0;
for (auto i: ALL_LEVELS)
hi = cruft::max (to_string (i).size (), hi);
return hi;
} ();
return width;
}
///////////////////////////////////////////////////////////////////////////////
void
cruft::log (cruft::level_t level, const std::string &msg)
{
if (level <= log_level ()) {
static const size_t time_len = strlen("YYYY-mm-dd HHMMhSS") + 1;
std::string time_string (time_len - 1, '\0');
time_t unix_time = time (nullptr);
if (0 == strftime (&time_string[0],
time_len,
"%Y-%m-%d %H%Mh%S",
localtime (&unix_time))) {
warn ("failed to log time");
return;
}
std::clog << time_string << " ["
<< level_colour (level)
<< std::setw (cruft::cast::lossless<int> (level_width ()))
<< std::left
<< level
<< std::setw (0)
<< cruft::term::csi::graphics::RESET
<< "] " << msg << std::endl;
}
if (needs_break (level))
breakpoint ();
}
///////////////////////////////////////////////////////////////////////////////
cruft::scoped_logger::scoped_logger (cruft::level_t _level,
std::string _message):
m_level (_level),
m_message (std::move (_message))
{ ; }
//-----------------------------------------------------------------------------
cruft::scoped_logger::~scoped_logger ()
{
log (m_level, m_message);
}
///////////////////////////////////////////////////////////////////////////////
cruft::scoped_timer::scoped_timer (cruft::level_t _level,
std::string _message):
m_level (_level),
m_message (std::move (_message)),
m_start (cruft::nanoseconds ())
{ ; }
//-----------------------------------------------------------------------------
cruft::scoped_timer::~scoped_timer ()
{
auto finish = cruft::nanoseconds ();
auto duration = finish - m_start;
log (m_level, "%fs, %s", float (duration) / 1'000'000'000.f, m_message);
}