Skip to content

Commit

Permalink
Log: Integrate with fmt
Browse files Browse the repository at this point in the history
See: aristocratos#535

The logger now uses the same syntax as the fmt format functions and
also uses fmt as the backend to write log files
  • Loading branch information
imwints committed Aug 29, 2023
1 parent 6c565e0 commit 458d3b5
Show file tree
Hide file tree
Showing 10 changed files with 91 additions and 65 deletions.
16 changes: 8 additions & 8 deletions src/btop.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -268,10 +268,10 @@ void clean_quit(int sig) {

if (not Global::exit_error_msg.empty()) {
sig = 1;
Logger::error(Global::exit_error_msg);
Logger::error("{}", Global::exit_error_msg);
fmt::println(std::cerr, "{}ERROR: {}{}{}", Global::fg_red, Global::fg_white, Global::exit_error_msg, Fx::reset);
}
Logger::info("Quitting! Runtime: " + sec_to_dhms(time_s() - Global::start_time));
Logger::info("Quitting! Runtime: {}", sec_to_dhms(time_s() - Global::start_time));

const auto excode = (sig != -1 ? sig : 0);

Expand Down Expand Up @@ -816,15 +816,15 @@ int main(int argc, char **argv) {
}
else Logger::set(Config::getS("log_level"));

Logger::info("Logger set to " + (Global::debug ? "DEBUG" : Config::getS("log_level")));
Logger::info("Logger set to {}", (Global::debug ? "DEBUG" : Config::getS("log_level")));

for (const auto& err_str : load_warnings) Logger::warning(err_str);
for (const auto& err_str : load_warnings) Logger::warning("{}", err_str);
}

//? Try to find and set a UTF-8 locale
if (std::setlocale(LC_ALL, "") != nullptr and not s_contains((string)std::setlocale(LC_ALL, ""), ";")
and str_to_upper(s_replace((string)std::setlocale(LC_ALL, ""), "-", "")).ends_with("UTF8")) {
Logger::debug("Using locale " + (string)std::setlocale(LC_ALL, ""));
Logger::debug("Using locale {}", std::setlocale(LC_ALL, ""));
}
else {
string found;
Expand All @@ -834,7 +834,7 @@ int main(int argc, char **argv) {
found = std::getenv(loc_env);
if (std::setlocale(LC_ALL, found.c_str()) == nullptr) {
set_failure = true;
Logger::warning("Failed to set locale " + found + " continuing anyway.");
Logger::warning("Failed to set locale {} continuing anyway.", found);
}
}
}
Expand Down Expand Up @@ -885,7 +885,7 @@ int main(int argc, char **argv) {
}
#endif
else if (not set_failure)
Logger::debug("Setting LC_ALL=" + found);
Logger::debug("Setting LC_ALL={}", found);
}

//? Initialize terminal and set options
Expand All @@ -894,7 +894,7 @@ int main(int argc, char **argv) {
clean_quit(1);
}

if (Term::current_tty != "unknown") Logger::info("Running on " + Term::current_tty);
if (Term::current_tty != "unknown") Logger::info("Running on {}", Term::current_tty);
if (not Global::arg_tty and Config::getB("force_tty")) {
Config::set("tty_mode", true);
Logger::info("Forcing tty mode: setting 16 color mode and using tty friendly graph symbols");
Expand Down
2 changes: 1 addition & 1 deletion src/btop_draw.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ namespace Draw {
c_upos = ulen(first);
}
catch (const std::exception& e) {
Logger::error("In TextEdit::operator() : " + string{e.what()});
Logger::error("In TextEdit::operator() : {}", e.what());
return "";
}
}
Expand Down
10 changes: 6 additions & 4 deletions src/btop_log.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
#include <mutex>
#include <string>

#include <fmt/core.h>

#include "btop_shared.hpp"
#include "btop_tools.hpp"

Expand Down Expand Up @@ -40,7 +42,7 @@ namespace Logger {

void set(const string& level) { loglevel = v_index(log_levels, level); }

void log_write(const size_t level, const string& msg) {
void log_write(const size_t level, const std::string_view msg) {
if (loglevel < level or logfile.empty()) {
return;
}
Expand All @@ -64,17 +66,17 @@ namespace Logger {
std::ofstream lwrite(logfile, std::ios::app);
if (first) {
first = false;
lwrite << "\n" << strf_time(tdf) << "===> btop++ v." << Global::Version << "\n";
fmt::print(lwrite, "\n{}===> btop++ v.{}\n", strf_time(tdf), Global::Version);
}
lwrite << strf_time(tdf) << log_levels.at(level) << ": " << msg << "\n";
fmt::print(lwrite, "{}{}: {}\n", strf_time(tdf), log_levels.at(level), msg);
}
else {
logfile.clear();
}
}
catch (const std::exception& e) {
logfile.clear();
throw std::runtime_error("Exception in Logger::log_write() : " + string{e.what()});
throw std::runtime_error(fmt::format("Exception in Logger::log_write() : {}", e.what()));
}
}
} // namespace Logger
30 changes: 24 additions & 6 deletions src/btop_log.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
#pragma once

#include <filesystem>
#include <string>
#include <string_view>
#include <vector>

#include <fmt/core.h>

namespace Logger {
const std::vector<std::string> log_levels = {
"DISABLED",
Expand All @@ -19,9 +21,25 @@ namespace Logger {
//* Set log level, valid arguments: "DISABLED", "ERROR", "WARNING", "INFO" and "DEBUG"
void set(const std::string& level);

void log_write(const size_t level, const std::string& msg);
inline void error(const std::string msg) { log_write(1, msg); }
inline void warning(const std::string msg) { log_write(2, msg); }
inline void info(const std::string msg) { log_write(3, msg); }
inline void debug(const std::string msg) { log_write(4, msg); }
void log_write(const size_t level, const std::string_view msg);

template <typename... T>
inline void error(const fmt::format_string<T...> fmt, T&&... args) {
log_write(1, fmt::format(fmt, std::forward<T>(args)...));
}

template <typename... T>
inline void warning(const fmt::format_string<T...> fmt, T&&... args) {
log_write(2, fmt::format(fmt, std::forward<T>(args)...));
}

template <typename... T>
inline void info(const fmt::format_string<T...> fmt, T&&... args) {
log_write(3, fmt::format(fmt, std::forward<T>(args)...));
}

template <typename... T>
inline void debug(const fmt::format_string<T...> fmt, T&&... args) {
log_write(4, fmt::format(fmt, std::forward<T>(args)...));
}
} // namespace Logger
2 changes: 1 addition & 1 deletion src/btop_menu.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1212,7 +1212,7 @@ namespace Menu {
theme_refresh = true;
else if (option == "log_level") {
Logger::set(optList.at(i));
Logger::info("Logger set to " + optList.at(i));
Logger::info("Logger set to {}", optList.at(i));
}
else if (is_in(option, "proc_sorting", "cpu_sensor") or option.starts_with("graph_symbol") or option.starts_with("cpu_graph_"))
screen_redraw = true;
Expand Down
12 changes: 6 additions & 6 deletions src/btop_theme.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ namespace Theme {
hexa.erase(0, 1);
for (auto& c : hexa) {
if (not isxdigit(c)) {
Logger::error("Invalid hex value: " + hexa);
Logger::error("Invalid hex value: {}", hexa);
return "";
}
}
Expand Down Expand Up @@ -184,9 +184,9 @@ namespace Theme {
to_string(stoi(hexa.substr(4, 2), nullptr, 16)) + "m";
}
}
else Logger::error("Invalid size of hex value: " + hexa);
else Logger::error("Invalid size of hex value: {}", hexa);
}
else Logger::error("Hex value missing: " + hexa);
else Logger::error("Hex value missing: {}", hexa);
return "";
}

Expand Down Expand Up @@ -255,7 +255,7 @@ namespace Theme {
else if (not source.at(name).empty()) {
t_rgb = ssplit(source.at(name));
if (t_rgb.size() != 3) {
Logger::error("Invalid RGB decimal value: \"" + source.at(name) + "\"");
Logger::error("Invalid RGB decimal value: \"{}\"", source.at(name));
} else {
colors[name] = dec_to_color(stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2]), t_to_256, depth);
rgbs[name] = array{stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2])};
Expand All @@ -264,7 +264,7 @@ namespace Theme {
}
}
if (not colors.contains(name) and not is_in(name, "meter_bg", "process_start", "process_mid", "process_end", "graph_text")) {
Logger::debug("Missing color value for \"" + name + "\". Using value from default.");
Logger::debug("Missing color value for \"{}\". Using value from default.", name);
colors[name] = hex_to_color(color, t_to_256, depth);
rgbs[name] = hex_to_dec(color);
}
Expand Down Expand Up @@ -380,7 +380,7 @@ namespace Theme {

std::ifstream themefile(filepath);
if (themefile.good()) {
Logger::debug("Loading theme file: " + filename);
Logger::debug("Loading theme file: {}", filename);
while (not themefile.bad()) {
themefile.ignore(SSmax, '[');
if (themefile.eof()) break;
Expand Down
2 changes: 1 addition & 1 deletion src/btop_tools.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ namespace Tools {
for (string readstr; getline(file, readstr); out += readstr);
}
catch (const std::exception& e) {
Logger::error("readfile() : Exception when reading " + string{path} + " : " + e.what());
Logger::error("readfile() : Exception when reading {} : {}", path.string(), e.what());
return fallback;
}
return (out.empty() ? fallback : out);
Expand Down
31 changes: 17 additions & 14 deletions src/freebsd/btop_collect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@ indent = tab
tab-size = 4
*/
#include <arpa/inet.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <libproc.h>
// man 3 getifaddrs: "BUGS: If both <net/if.h> and <ifaddrs.h> are being included, <net/if.h> must be included before <ifaddrs.h>"
#include <net/if.h>
Expand All @@ -42,24 +39,30 @@ tab-size = 4
#include <sys/mount.h>
#include <sys/vmmeter.h>
#include <sys/limits.h>
#include <vector>
#include <vm/vm_param.h>
#include <kvm.h>
#include <paths.h>
#include <fcntl.h>
#include <unistd.h>
#include <devstat.h>

#include <stdexcept>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <memory>
#include <numeric>
#include <ranges>
#include <regex>
#include <stdexcept>
#include <string>
#include <memory>
#include <vector>

#include <fmt/core.h>

#include "../btop_config.hpp"
#include "../btop_log.hpp"
#include "../btop_shared.hpp"
#include "../btop_tools.hpp"

Expand Down Expand Up @@ -447,8 +450,8 @@ namespace Cpu {
if (cpu.core_percent.at(i).size() > 40) cpu.core_percent.at(i).pop_front();

} catch (const std::exception &e) {
Logger::error("Cpu::collect() : " + (string)e.what());
throw std::runtime_error("collect() : " + (string)e.what());
Logger::error("Cpu::collect() : {}", e.what());
throw std::runtime_error(fmt::format("collect() : {}", e.what()));
}

}
Expand Down Expand Up @@ -551,7 +554,7 @@ namespace Mem {
size_t len = 512;
if (fgets(poolName, len, poolPipe())) {
poolName[strcspn(poolName, "\n")] = 0;
Logger::debug("zpool found: " + string(poolName));
Logger::debug("zpool found: {}", poolName);
Mem::zpools.push_back(std::regex_replace(poolName, toReplace, "%25"));
}
}
Expand All @@ -576,7 +579,7 @@ namespace Mem {
devstat_compute_statistics(&d, nullptr, etime, DSM_TOTAL_BYTES_READ, &total_bytes_read, DSM_TOTAL_BYTES_WRITE, &total_bytes_write, DSM_NONE);
assign_values(disk, total_bytes_read, total_bytes_write);
string mountpoint = mapping.at(disk.dev);
Logger::debug("dev " + devStatName + " -> " + mountpoint + " read=" + std::to_string(total_bytes_read) + " write=" + std::to_string(total_bytes_write));
Logger::debug("dev {} -> {} read={} write={}", devStatName, mountpoint, total_bytes_read, total_bytes_write);
}
}

Expand Down Expand Up @@ -766,7 +769,7 @@ namespace Mem {
continue;
struct statvfs vfs;
if (statvfs(mountpoint.c_str(), &vfs) < 0) {
Logger::warning("Failed to get disk/partition stats with statvfs() for: " + mountpoint);
Logger::warning("Failed to get disk/partition stats with statvfs() for: {}", mountpoint);
continue;
}
disk.total = vfs.f_blocks * vfs.f_frsize;
Expand Down Expand Up @@ -840,7 +843,7 @@ namespace Net {
getifaddr_wrapper if_wrap{};
if (if_wrap.status != 0) {
errors++;
Logger::error("Net::collect() -> getifaddrs() failed with id " + to_string(if_wrap.status));
Logger::error("Net::collect() -> getifaddrs() failed with id {}", if_wrap.status);
redraw = true;
return empty_net;
}
Expand Down Expand Up @@ -875,7 +878,7 @@ namespace Net {
net[iface].ipv4 = ip;
} else {
int errsv = errno;
Logger::error("Net::collect() -> Failed to convert IPv4 to string for iface " + string(iface) + ", errno: " + strerror(errsv));
Logger::error("Net::collect() -> Failed to convert IPv4 to string for iface {}, errno: {}", iface, strerror(errsv));
}
}
}
Expand All @@ -886,7 +889,7 @@ namespace Net {
net[iface].ipv6 = ip;
} else {
int errsv = errno;
Logger::error("Net::collect() -> Failed to convert IPv6 to string for iface " + string(iface) + ", errno: " + strerror(errsv));
Logger::error("Net::collect() -> Failed to convert IPv6 to string for iface {}, errno: {}", iface, strerror(errsv));
}
}
} //else, ignoring family==AF_LINK (see man 3 getifaddrs)
Expand Down
Loading

0 comments on commit 458d3b5

Please sign in to comment.