ASIO Client Server Framework
Loading...
Searching...
No Matches
logger.h
1#pragma once
2#include <boost/asio.hpp>
3#include <boost/system/error_code.hpp>
4#include <boost/lockfree/spsc_queue.hpp>
5#include <chrono>
6#include <format>
7#include <cstdint>
8#include <optional>
9#include <string>
10#include <fstream>
11#include <iostream>
12#include <filesystem>
13
14#include "protocol.h"
15
16namespace acsf {
17
19 enum class LogLevel {
28 };
29
30
32 inline std::string levelToString(LogLevel level)
33 {
34 switch (level)
35 {
36 case LogLevel::DEBUG: return "DEBUG";
37 case LogLevel::INFO: return "INFO";
38 case LogLevel::WARN: return "WARN";
39 case LogLevel::ERROR: return "ERROR";
40 }
41 return "UNKNOWN";
42 }
43
45 struct Log
46 {
47 // General
49 std::optional<uint64_t> isFrom;
51 std::optional<LogLevel> level;
53 std::optional<std::chrono::system_clock::time_point> timestamp;
55 std::optional<std::string> message; // human readable message / context
56
57 // boost::system::error_code details
59 std::optional<int> errorValue; // ec.value()
61 std::optional<std::string> errorMessage; // ec.message()
62
63 // Endpoint info
65 std::optional<std::string> localAddress;
67 std::optional<uint16_t> localPort;
69 std::optional<std::string> remoteAddress;
71 std::optional<uint16_t> remotePort;
72
74 std::string toString() const
75 {
76 std::string result;
77
78 if (timestamp.has_value())
79 result += std::format("[{:%Y-%m-%d %H:%M:%S}] ", std::chrono::floor<std::chrono::milliseconds>(timestamp.value()));
80
81 if (level.has_value())
82 result += "[" + levelToString(level.value()) + "] ";
83
84 if (isFrom.has_value())
85 result += "[from=" + std::to_string(isFrom.value()) + "] ";
86
87 if (message.has_value())
88 result += message.value();
89
90 if (remoteAddress.has_value())
91 result += " remote=" + remoteAddress.value();
92
93 if (remotePort.has_value())
94 result += ":" + std::to_string(remotePort.value());
95
96 if (errorValue.has_value())
97 result += " [error " + std::to_string(errorValue.value()) + "]";
98
99 if (errorMessage.has_value())
100 result += " " + errorMessage.value();
101
102 return result;
103 }
104 };
105
106
118 {
120 bool enabled = false;
121
123 std::filesystem::path folder = "LOG_FOLDER";
124
127 };
128
129
131 class Logger {
132 private:
133 LoggerConfig config_;
134 std::ofstream CURRENT_LOG_FILE_;
135 std::filesystem::path LOG_FOLDER_PATH_;
136 boost::asio::strand<boost::asio::io_context::executor_type> loggerStrand_;
137 boost::lockfree::spsc_queue<Log, boost::lockfree::capacity<LOG_BUFFER_SIZE>> logBuffer_;
138
139 std::filesystem::path newLogFilePath() const {
140 std::string name = std::format("LOG_FILE-{:%Y-%m-%d_%H-%M-%S}", std::chrono::floor<std::chrono::seconds>(std::chrono::system_clock::now()));
141
142 // Prevent any possiblity of dupe file
143 std::filesystem::path path = LOG_FOLDER_PATH_ / (name + ".log");
144 for(int i = 1; std::filesystem::exists(path); ++i){
145 path = LOG_FOLDER_PATH_ / (name + "-" + std::to_string(i) + ".log");
146 }
147 return path;
148 }
149
150 void rotateLogFile(){
151 std::ofstream newLogFile(newLogFilePath());
152 if(!newLogFile.is_open()) {
153 return;
154 }
155
156 CURRENT_LOG_FILE_.close();
157 CURRENT_LOG_FILE_ = std::move(newLogFile);
158 }
159
160 void unsafeFlush(bool checkSize = false){
161 if(!CURRENT_LOG_FILE_.is_open()) return;
162
163 // Write buffer to file
164 Log log;
165 while(logBuffer_.pop(log)){
166 CURRENT_LOG_FILE_ << log.toString() << '\n';
167 }
168 CURRENT_LOG_FILE_.flush();
169
170 // Check if file is max size
171 if(checkSize && static_cast<std::uintmax_t>(CURRENT_LOG_FILE_.tellp()) >= config_.maxFileSize){
172 rotateLogFile();
173 }
174 }
175
176 void unsafePushLog(Log log){
177 if(!log.timestamp.has_value())
178 log.timestamp = std::chrono::system_clock::now();
179
180 if(!logBuffer_.push(log)){
181 unsafeFlush(true);
182 logBuffer_.push(std::move(log));
183 }
184 }
185
186 public:
187
193 Logger(boost::asio::io_context& ioc, LoggerConfig config = {}) : config_(std::move(config)), LOG_FOLDER_PATH_(config_.folder), loggerStrand_(ioc.get_executor()) {
194 if(!config_.enabled) return;
195
196 if(LOG_FOLDER_PATH_.empty()){
197 LOG_FOLDER_PATH_ = "LOG_FOLDER";
198 }
199 std::filesystem::create_directories(LOG_FOLDER_PATH_);
200 LOG_FOLDER_PATH_ = std::filesystem::absolute(LOG_FOLDER_PATH_);
201
202 CURRENT_LOG_FILE_.open(newLogFilePath());
203 }
204
205 ~Logger(){
206 unsafeFlush(false);
207 }
208
209 Logger(const Logger&) = delete;
210 Logger& operator=(const Logger&) = delete;
211
214 unsafeFlush(true);
215 }
216
218 void flush(){
219 boost::asio::post(loggerStrand_, [this](){unsafeFlush(true);});
220 }
221
223 void push(Log log){
224 if(!config_.enabled) return;
225
226 boost::asio::post(loggerStrand_, [this, log = std::move(log)]() mutable {unsafePushLog(std::move(log));});
227 }
228 };
229}
void push(Log log)
Adds an entry to the log. Returns immediately. Ignored when logging is disabled.
Definition logger.h:223
void flush()
Asks the logger to write buffered entries to disk. Returns immediately.
Definition logger.h:218
Logger(boost::asio::io_context &ioc, LoggerConfig config={})
Creates a logger. If config.enabled is false it does nothing.
Definition logger.h:193
void unsafeFlushNow()
Writes all buffered entries to disk immediately on the calling thread. Only safe when no other thread...
Definition logger.h:213
Everything in the framework lives in this namespace.
std::string levelToString(LogLevel level)
Converts a LogLevel to its upper case name, e.g. "WARN".
Definition logger.h:32
std::uintmax_t MAX_LOG_FILE_SIZE
Default size in bytes at which a log file is rotated. Change with setMaxLogFileSize().
Definition protocol.h:22
LogLevel
Severity of a log entry.
Definition logger.h:19
@ WARN
Definition logger.h:25
@ INFO
Definition logger.h:23
@ ERROR
Definition logger.h:27
@ DEBUG
Definition logger.h:21
One log entry. Every field is optional and only the fields that are set appear in the output.
Definition logger.h:46
std::optional< std::string > errorMessage
Definition logger.h:61
std::optional< std::chrono::system_clock::time_point > timestamp
Definition logger.h:53
std::optional< uint16_t > localPort
Definition logger.h:67
std::optional< int > errorValue
Definition logger.h:59
std::optional< std::string > localAddress
Definition logger.h:65
std::optional< uint16_t > remotePort
Definition logger.h:71
std::optional< std::string > message
Definition logger.h:55
std::optional< uint64_t > isFrom
Definition logger.h:49
std::optional< std::string > remoteAddress
Definition logger.h:69
std::string toString() const
Formats the entry as a single line of text.
Definition logger.h:74
std::optional< LogLevel > level
Definition logger.h:51
Logging settings passed to acsf::Server and acsf::Client.
Definition logger.h:118
std::filesystem::path folder
Definition logger.h:123
std::uintmax_t maxFileSize
Definition logger.h:126
bool enabled
Definition logger.h:120