1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
#include "logger.hpp"
#include <ctime>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
namespace bot::log {
void log(const LogLevel &level, const std::string &source,
const std::string &message) {
std::string dir_name = "logs";
if (!std::filesystem::exists(dir_name)) {
std::filesystem::create_directory(dir_name);
}
if (std::filesystem::exists(dir_name) &&
!std::filesystem::is_directory(dir_name)) {
throw std::runtime_error("The path '" + dir_name +
"' is not a directory!");
return;
}
std::ostringstream line;
// getting time
std::time_t current_time = std::time(nullptr);
std::tm *local_time = std::localtime(¤t_time);
line << "[" << std::put_time(local_time, "%H:%M:%S") << "] ";
std::string level_str;
switch (level) {
case DEBUG:
level_str = "DEBUG";
break;
case WARN:
level_str = "WARN";
break;
case ERROR:
level_str = "ERROR";
break;
default:
level_str = "INFO";
break;
}
line << level_str << " - ";
line << source << ": " << message << "\n";
#ifdef DEBUG_MODE
std::cout << line.str();
#else
if (level != LogLevel::DEBUG) {
std::cout << line.str();
}
#endif
// saving into the log file
std::ostringstream file_name_oss;
file_name_oss << dir_name << "/";
file_name_oss << "log_";
file_name_oss << std::put_time(local_time, "%Y-%m-%d");
file_name_oss << ".log";
std::ofstream ofs;
ofs.open(file_name_oss.str(), std::ios::app);
if (ofs.is_open()) {
ofs << line.str();
ofs.close();
} else {
std::cerr << "Failed to write to the log file!\n";
}
}
void info(const std::string &source, const std::string &message) {
log(LogLevel::INFO, source, message);
}
void debug(const std::string &source, const std::string &message) {
log(LogLevel::DEBUG, source, message);
}
void warn(const std::string &source, const std::string &message) {
log(LogLevel::WARN, source, message);
}
void error(const std::string &source, const std::string &message) {
log(LogLevel::ERROR, source, message);
}
}
|