libcruft-util/cruft/util/log/sink/console.cpp

92 lines
2.4 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 2019, Danny Robson <danny@nerdcruft.net>
*/
#include "console.hpp"
#include "../level.hpp"
#include "../packet.hpp"
#include "../../term.hpp"
#include "../../debug/warn.hpp"
#include "../../cast.hpp"
#include <iomanip>
#include <iostream>
#include <ctime>
#include <cstring>
using cruft::log::sink::console;
///////////////////////////////////////////////////////////////////////////////
static
cruft::term::csi::graphics
level_colour (cruft::log::level_t level)
{
using cruft::term::csi::graphics;
switch (level) {
case cruft::log::EMERGENCY:
case cruft::log::ALERT:
case cruft::log::CRITICAL:
case cruft::log::ERROR:
return graphics (graphics::FOREGROUND, graphics::RED);
case cruft::log::WARNING:
return graphics (graphics::FOREGROUND, graphics::YELLOW);
case cruft::log::NOTICE:
case cruft::log::INFORMATIONAL:
return graphics (graphics::FOREGROUND, graphics::GREEN);
case cruft::log::DEBUG:
return graphics (graphics::FOREGROUND, graphics::WHITE);
}
unreachable ();
}
///////////////////////////////////////////////////////////////////////////////
console::console (std::string name)
: crtp (std::move (name))
{ ; }
///////////////////////////////////////////////////////////////////////////////
void
console::write (packet const &val)
{
if (val.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 (val.level)
<< std::setw (cruft::cast::lossless<int> (level_width ()))
<< std::left
<< val.level
<< std::setw (0)
<< cruft::term::csi::graphics::RESET
<< "] " << val.message << std::endl;
}
if (needs_break (val.level))
breakpoint ();
}