h804tun/common.cpp

91 lines
2.1 KiB
C++
Raw Normal View History

2018-10-17 03:11:21 +00:00
#include "common.h"
#include <unistd.h>
#include <cerrno>
#include <cstring>
namespace h804 {
void daemon_notify_ready() {
#ifdef H804_SYSTEMD_ENABLE
sd_notify(0, "READY=1");
#endif
}
2018-10-17 17:01:46 +00:00
void daemon_notify(const std::string& args) {
#ifdef H804_SYSTEMD_ENABLE
sd_notify(0, args.c_str());
#endif
}
2018-10-17 03:11:21 +00:00
// clang-format off
const char* _log_text[(size_t)LogLevel::_SIZE] = {
#ifdef H804_SYSTEMD_ENABLE
SD_DEBUG "[DEBUG] ",
SD_INFO "[INFO ] ",
SD_NOTICE "[NOTIC] ",
SD_WARNING "[WARN ] ",
SD_ERR "[ERROR] "
#else
"[DEBUG] ",
"[INFO ] ",
"[NOTIC] ",
"[WARN ] ",
"[ERROR] "
#endif
};
const char* _log_colors[(size_t)LogLevel::_SIZE] = {
"[DEBUG] ",
"\e[0;32m[INFO ] ",
"\e[0;36m[NOTIC] ",
"\e[1;93m[WARN ] ",
"\e[1;91m[ERROR] "
};
// clang-format on
const char* log_reset = "\e[0m";
void _log(const LogLevel, const std::string&);
void _log(const LogLevel, const char*);
void _log(const LogLevel level, const std::string& text) {
if (isatty(STDERR_FILENO)) {
std::cerr << _log_colors[(size_t)level] << text << log_reset << std::endl;
} else {
std::cerr << _log_text[(size_t)level] << text << std::endl;
}
}
void _log(const LogLevel level, const char* text) {
if (isatty(STDERR_FILENO)) {
std::cerr << _log_colors[(size_t)level] << text << log_reset << std::endl;
} else {
std::cerr << _log_text[(size_t)level] << text << std::endl;
}
}
_Logger::_Logger(LogLevel level) : level(level) {}
void _Logger::operator<<(const std::string& str) const { _log(level, str); }
void _Logger::operator<<(const char* str) const { _log(level, str); }
2018-10-17 17:01:46 +00:00
errno_exception::errno_exception() noexcept : _what(strerror(errno)), saved_errno(errno) {}
2018-10-17 03:11:21 +00:00
errno_exception::errno_exception(const char* msg) noexcept
2018-10-17 17:01:46 +00:00
: _what(std::string(msg) + ": " + strerror(errno)), saved_errno(errno) {}
2018-10-17 03:11:21 +00:00
const char* errno_exception::what() const noexcept { return this->_what.c_str(); }
void check(long x) {
if (x < 0) {
throw errno_exception();
}
}
void check(long x, const char* msg) {
if (x < 0) {
throw errno_exception(msg);
}
}
} // namespace h804