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 to the log file
  • Loading branch information
imwints committed Aug 29, 2023
1 parent 6c565e0 commit 3f389f4
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 43 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
32 changes: 16 additions & 16 deletions src/linux/btop_collect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ namespace Cpu {
if (++failed < 5)
return ""s;
else {
Logger::warning("get_cpuHZ() : " + string{e.what()});
Logger::warning("get_cpuHZ() : {}", e.what());
return ""s;
}
}
Expand Down Expand Up @@ -785,17 +785,17 @@ namespace Cpu {

//? Notify main thread to redraw screen if we found more cores than previously detected
if (cmp_greater(cpu.core_percent.size(), Shared::coreCount)) {
Logger::debug("Changing CPU max corecount from " + to_string(Shared::coreCount) + " to " + to_string(cpu.core_percent.size()) + ".");
Logger::debug("Changing CPU max corecount from {} to {}.", Shared::coreCount, cpu.core_percent.size());
Runner::coreNum_reset = true;
Shared::coreCount = cpu.core_percent.size();
while (cmp_less(current_cpu.temp.size(), cpu.core_percent.size() + 1)) current_cpu.temp.push_back({0});
}

}
catch (const std::exception& e) {
Logger::debug("Cpu::collect() : " + string{e.what()});
Logger::debug("Cpu::collect() : {}", e.what());
if (cread.bad()) throw std::runtime_error("Failed to read /proc/stat");
else throw std::runtime_error("Cpu::collect() : " + string{e.what()});
else throw std::runtime_error(fmt::format("Cpu::collect() : {}", e.what()));
}

if (Config::getB("check_temp") and got_sensors)
Expand Down Expand Up @@ -1043,7 +1043,7 @@ namespace Mem {
} else if (fstype == "zfs") {
disks.at(mountpoint).stat = get_zfs_stat_file(dev, zfs_dataset_name_start, zfs_hide_datasets);
if (disks.at(mountpoint).stat.empty()) {
Logger::debug("Failed to get ZFS stat file for device " + dev);
Logger::debug("Failed to get ZFS stat file for device {}", dev);
}
break;
}
Expand All @@ -1057,7 +1057,7 @@ namespace Mem {
|| (!zfs_hide_datasets && is_directory(disks.at(mountpoint).stat)))) {
disks.at(mountpoint).stat = get_zfs_stat_file(dev, zfs_dataset_name_start, zfs_hide_datasets);
if (disks.at(mountpoint).stat.empty()) {
Logger::debug("Failed to get ZFS stat file for device " + dev);
Logger::debug("Failed to get ZFS stat file for device {}", dev);
}
}
}
Expand All @@ -1084,7 +1084,7 @@ namespace Mem {
if (std::error_code ec; not fs::exists(mountpoint, ec) or v_contains(ignore_list, mountpoint)) continue;
struct statvfs vfs;
if (statvfs(mountpoint.c_str(), &vfs) < 0) {
Logger::warning("Failed to get disk/partition stats for mount \""+ mountpoint + "\" with statvfs error code: " + to_string(errno) + ". Ignoring...");
Logger::warning("Failed to get disk/partition stats for mount \"{}\" with statvfs error code: {}. Ignoring...", mountpoint, to_string(errno));
ignore_list.push_back(mountpoint);
new_ignored = true;
continue;
Expand Down Expand Up @@ -1209,14 +1209,14 @@ namespace Mem {
while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();
}
} else {
Logger::debug("Error in Mem::collect() : when opening " + string{disk.stat});
Logger::debug("Error in Mem::collect() : when opening {}", disk.stat.string());
}
diskread.close();
}
old_uptime = uptime;
}
catch (const std::exception& e) {
Logger::warning("Error in Mem::collect() : " + string{e.what()});
Logger::warning("Error in Mem::collect() : {}", e.what());
}
}

Expand All @@ -1230,7 +1230,7 @@ namespace Mem {
if (access(zfs_pool_stat_path.c_str(), R_OK) == 0) {
return zfs_pool_stat_path;
} else {
Logger::debug("Cant access folder: " + zfs_pool_stat_path.string());
Logger::debug("Cant access folder: {}", zfs_pool_stat_path.string());
return "";
}
}
Expand Down Expand Up @@ -1261,7 +1261,7 @@ namespace Mem {
if (access(file.path().c_str(), R_OK) == 0) {
return file.path();
} else {
Logger::debug("Can't access file: " + file.path().string());
Logger::debug("Can't access file: {}", file.path().string());
return "";
}
}
Expand All @@ -1270,7 +1270,7 @@ namespace Mem {
}
}

Logger::debug("Could not read directory: " + zfs_pool_stat_path.string());
Logger::debug("Could not read directory: {}", zfs_pool_stat_path.string());
return "";
}

Expand Down Expand Up @@ -1319,7 +1319,7 @@ namespace Mem {
// increment read objects counter if no errors were encountered
objects_read++;
} else {
Logger::debug("Could not read file: " + file.path().string());
Logger::debug("Could not read file: {}", file.path().string());
}
diskread.close();
}
Expand Down Expand Up @@ -1388,7 +1388,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 @@ -1425,7 +1425,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 @@ -1436,7 +1436,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_PACKET (see man 3 getifaddrs) which is the first one in the `for` loop.
Expand Down

0 comments on commit 3f389f4

Please sign in to comment.