lix/src/libutil/logging.cc

100 lines
2 KiB
C++
Raw Normal View History

#include "logging.hh"
#include "util.hh"
2017-05-16 14:09:57 +00:00
#include <atomic>
namespace nix {
2017-04-12 12:52:49 +00:00
Logger * logger = makeDefaultLogger();
2017-04-12 12:53:10 +00:00
void Logger::warn(const std::string & msg)
{
log(lvlInfo, ANSI_RED "warning:" ANSI_NORMAL " " + msg);
}
class SimpleLogger : public Logger
{
public:
bool systemd, tty;
SimpleLogger()
{
systemd = getEnv("IN_SYSTEMD") == "1";
tty = isatty(STDERR_FILENO);
}
void log(Verbosity lvl, const FormatOrString & fs) override
{
if (lvl > verbosity) return;
std::string prefix;
if (systemd) {
char c;
switch (lvl) {
case lvlError: c = '3'; break;
case lvlInfo: c = '5'; break;
case lvlTalkative: case lvlChatty: c = '6'; break;
default: c = '7';
}
prefix = std::string("<") + c + ">";
}
writeToStderr(prefix + (tty ? fs.s : filterANSIEscapes(fs.s)) + "\n");
}
2017-05-16 14:09:57 +00:00
void event(const Event & ev) override
{
}
};
Verbosity verbosity = lvlInfo;
void warnOnce(bool & haveWarned, const FormatOrString & fs)
{
if (!haveWarned) {
2017-04-12 12:53:10 +00:00
warn(fs.s);
haveWarned = true;
}
}
void writeToStderr(const string & s)
{
try {
writeFull(STDERR_FILENO, s, false);
} catch (SysError & e) {
/* Ignore failing writes to stderr. We need to ignore write
errors to ensure that cleanup code that logs to stderr runs
to completion if the other side of stderr has been closed
unexpectedly. */
}
}
Logger * makeDefaultLogger()
{
return new SimpleLogger();
}
std::atomic<uint64_t> nextId{(uint64_t) getpid() << 32};
2017-05-16 14:09:57 +00:00
Activity::Activity() : id(nextId++) { };
2017-08-14 13:28:16 +00:00
Activity::Activity(ActivityType type, std::string msg)
: Activity()
{
logger->event(evStartActivity, id, type, msg);
2017-08-14 13:28:16 +00:00
}
Activity::~Activity()
{
logger->event(evStopActivity, id);
}
void Activity::progress(uint64_t done, uint64_t expected, uint64_t running, uint64_t failed) const
{
logger->event(evProgress, id, done, expected, running, failed);
}
}