Skip to content
API Documentation
BastionGuard™
Logger.cpp
Go to the documentation of this file.
2#include <chrono>
3#include <ctime>
4#include <fstream>
5#include <iomanip>
6#include <iostream>
7#include <sstream>
8
9namespace bsc::logging {
10
12 static Logger logger;
13 return logger;
14}
15
16void Logger::set_level(Level level) { level_ = level; }
17void Logger::set_utc(bool enabled) { utc_ = enabled; }
18void Logger::set_microseconds(bool enabled) { micro_ = enabled; }
19void Logger::set_log_file(const std::string& path) { file_path_ = path; }
20void Logger::debug(const std::string& msg) { log(Level::Debug, msg); }
21void Logger::info(const std::string& msg) { log(Level::Info, msg); }
22void Logger::warning(const std::string& msg) { log(Level::Warning, msg); }
23void Logger::error(const std::string& msg) { log(Level::Error, msg); }
24
25void Logger::log(Level level, const std::string& msg) {
26 if (static_cast<int>(level) < static_cast<int>(level_)) return;
27 std::lock_guard lock(mutex_);
28 std::ostringstream line;
29 line << timestamp() << " [" << level_name(level) << "] " << msg << '\n';
30 std::cerr << line.str();
31 if (!file_path_.empty()) {
32 std::ofstream out(file_path_, std::ios::app);
33 if (out) out << line.str();
34 }
35}
36
37std::string Logger::timestamp() const {
38 using namespace std::chrono;
39 auto now = system_clock::now();
40 auto tt = system_clock::to_time_t(now);
41 std::tm tm{};
42 if (utc_) gmtime_r(&tt, &tm); else localtime_r(&tt, &tm);
43 std::ostringstream oss;
44 oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
45 if (micro_) {
46 auto us = duration_cast<microseconds>(now.time_since_epoch()) % seconds(1);
47 oss << '.' << std::setw(6) << std::setfill('0') << us.count();
48 }
49 return oss.str();
50}
51
52std::string Logger::level_name(Level level) const {
53 switch (level) {
54 case Level::Debug: return "DEBUG";
55 case Level::Info: return "INFO";
56 case Level::Warning: return "WARN";
57 case Level::Error: return "ERROR";
58 }
59 return "INFO";
60}
61
62} // namespace bsc::logging
void warning(const std::string &msg)
Definition Logger.cpp:22
void set_microseconds(bool enabled)
Definition Logger.cpp:18
std::mutex mutex_
Definition Logger.hpp:30
void info(const std::string &msg)
Definition Logger.cpp:21
void set_log_file(const std::string &path)
Definition Logger.cpp:19
void debug(const std::string &msg)
Definition Logger.cpp:20
void error(const std::string &msg)
Definition Logger.cpp:23
static Logger & instance()
Definition Logger.cpp:11
std::string file_path_
Definition Logger.hpp:29
std::string timestamp() const
Definition Logger.cpp:37
void log(Level level, const std::string &msg)
Definition Logger.cpp:25
void set_utc(bool enabled)
Definition Logger.cpp:17
std::string level_name(Level level) const
Definition Logger.cpp:52
void set_level(Level level)
Definition Logger.cpp:16