Fray Engine
Loading...
Searching...
No Matches
log_manager.hpp
Go to the documentation of this file.
1/* log_manager.hpp */
2
3#ifndef _FRAY_LOG_MANAGER_HPP_
4#define _FRAY_LOG_MANAGER_HPP_
5
6#include <cstdio>
7#include <ctime>
8#include <chrono>
9#include <string>
10#include <atomic>
11#include <cstdarg>
12#include <functional>
13#include <memory>
14#include <mutex>
15
16#include "types.hpp"
17#include "errors.hpp"
18
19namespace fray
20{
21 namespace log
22 {
26 constexpr const F_char *ANSI_RESET = "\033[0m";
30 constexpr const F_char *ANSI_BOLD = "\033[1m";
34 constexpr const F_char *ANSI_UNDERLINE = "\033[4m";
38 constexpr const F_char *ANSI_BLINK = "\033[5m";
42 constexpr const F_char *ANSI_INVERSE = "\033[7m";
43
47 constexpr const F_char *ANSI_FG_BLACK = "\033[30m";
51 constexpr const F_char *ANSI_FG_RED = "\033[31m";
55 constexpr const F_char *ANSI_FG_GREEN = "\033[32m";
59 constexpr const F_char *ANSI_FG_YELLOW = "\033[33m";
63 constexpr const F_char *ANSI_FG_BLUE = "\033[34m";
67 constexpr const F_char *ANSI_FG_MAGENTA = "\033[35m";
71 constexpr const F_char *ANSI_FG_CYAN = "\033[36m";
75 constexpr const F_char *ANSI_FG_WHITE = "\033[37m";
79 constexpr const F_char *ANSI_FG_ORANGE = "\x1b[38;5;208m";
80
84 constexpr const F_char *ANSI_BG_BLACK = "\033[40m";
88 constexpr const F_char *ANSI_BG_RED = "\033[41m";
92 constexpr const F_char *ANSI_BG_GREEN = "\033[42m";
96 constexpr const F_char *ANSI_BG_YELLOW = "\033[43m";
100 constexpr const F_char *ANSI_BG_BLUE = "\033[44m";
104 constexpr const F_char *ANSI_BG_MAGENTA = "\033[45m";
108 constexpr const F_char *ANSI_BG_CYAN = "\033[46m";
112 constexpr const F_char *ANSI_BG_WHITE = "\033[47m";
116 constexpr const F_char *ANSI_BG_ORANGE = "\033[48;5;208m";
117
121 constexpr F_long TIMESTAMP_SIZE = 32;
129 constexpr F_long DATE_SIZE = 32;
137 constexpr F_long TIME_SIZE = 32;
142
149 F_char *timestamp,
150 std::chrono::system_clock::time_point now = std::chrono::system_clock::now())
151 {
152 using namespace std::chrono;
153 auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
154
155 std::time_t t = system_clock::to_time_t(now);
156 std::tm tm;
157#if defined(_WIN32)
158 localtime_s(&tm, &t);
159#else
160 localtime_r(&t, &tm);
161#endif
162
163 std::snprintf(
164 timestamp, 32, "[%02d:%02d:%02d:%03d] [%02d.%02d.%02d]",
165 tm.tm_hour, tm.tm_min, tm.tm_sec,
166 static_cast<F_long>(ms.count()),
167 tm.tm_year % 100, tm.tm_mon + 1, tm.tm_mday);
168 }
169
175 F_char *date)
176 {
177 using namespace std::chrono;
178 auto now = system_clock::now();
179 std::time_t t = system_clock::to_time_t(now);
180 std::tm tm;
181#if defined(_WIN32)
182 localtime_s(&tm, &t);
183#else
184 localtime_r(&t, &tm);
185#endif
186
187 std::snprintf(
188 date, 32, "%02d.%02d.%02d",
189 tm.tm_year % 100, tm.tm_mon + 1, tm.tm_mday);
190 }
191
198 F_char *time,
199 std::chrono::system_clock::time_point now = std::chrono::system_clock::now())
200 {
201 using namespace std::chrono;
202 auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
203
204 std::time_t t = system_clock::to_time_t(now);
205 std::tm tm;
206#if defined(_WIN32)
207 localtime_s(&tm, &t);
208#else
209 localtime_r(&t, &tm);
210#endif
211
212 std::snprintf(
213 time, 32, "%02d:%02d:%02d.%03d",
214 tm.tm_hour, tm.tm_min, tm.tm_sec,
215 static_cast<int>(ms.count()));
216 }
217
223 {
224 static std::atomic<F_long> next{0};
225 thread_local const F_long id = next++;
226 return id;
227 }
228
241 using Sink = std::function<void(const F_char *PID, const F_char *level, F_long thread, const std::string &project, const F_char *message, bool consoleVisible)>;
242
246 inline std::mutex &sinkMutex()
247 {
248 static std::mutex mutex;
249 return mutex;
250 }
251
255 inline std::shared_ptr<Sink> &sinkSlot()
256 {
257 static std::shared_ptr<Sink> slot;
258 return slot;
259 }
260
269 Sink sink)
270 {
271 std::lock_guard<std::mutex> lock(sinkMutex());
272 sinkSlot() = sink ? std::make_shared<Sink>(std::move(sink)) : nullptr;
273 }
274
281 inline std::string &threadProject()
282 {
283 thread_local std::string project;
284 return project;
285 }
286
294 {
295 private:
299 std::string _previous;
300
301 public:
306 explicit ProjectScope(
307 const std::string &project)
309 {
310 // An unknown project (still opening) leaves the thread's tag alone.
311 if (!project.empty())
312 threadProject() = project;
313 }
314
318 const ProjectScope &) = delete;
323 const ProjectScope &) = delete;
328 };
329
334 inline bool &sinkSuppressed()
335 {
336 thread_local bool suppressed = false;
337 return suppressed;
338 }
339
345 {
346 private:
349
350 public:
354 {
355 sinkSuppressed() = true;
356 }
357
359 const SinkSuppression &) = delete;
362 const SinkSuppression &) = delete;
365 };
366
368 inline bool &consoleVisible()
369 {
370 thread_local bool visible = true;
371 return visible;
372 }
373
386
398 const F_char *PID,
399 const F_char *PIDColor,
400 const F_char *level,
401 const F_char *levelColor,
402 const F_char *message)
403 {
404 timeBuffer tb;
405 getTime(tb);
406
407 // Build the whole line first and write it under a lock so threads cannot interleave.
408 std::string line = "[";
409 line += tb;
410 line += "] [T";
411 line += std::to_string(threadId());
412 line += "] [";
413 line += PIDColor;
414 line += PID;
415 line += ANSI_RESET;
416 line += "] [";
417 line += levelColor;
418 line += level;
419 line += ANSI_RESET;
420 line += "] ";
421 line += message;
422 line += '\n';
423
424 static std::mutex outputMutex;
425 std::unique_lock<std::mutex> lock(outputMutex);
426 std::fwrite(line.data(), 1, line.size(), stdout);
427 std::fflush(stdout);
428 lock.unlock();
429
430 std::shared_ptr<Sink> sink;
431 {
432 std::lock_guard<std::mutex> sinkLock(sinkMutex());
433 sink = sinkSlot();
434 }
435 if (sink && !sinkSuppressed())
436 (*sink)(PID, level, threadId(), threadProject(), message, consoleVisible());
437 }
438
449 const F_char *PID,
450 const F_char *PIDColor,
451 const F_char *level,
452 const F_char *levelColor,
453 const F_char *fmt,
454 va_list args)
455 {
456 char message[1024];
457 std::vsnprintf(message, sizeof(message), fmt, args);
458 printf(PID, PIDColor, level, levelColor, message);
459 }
460
467 const F_char *fmt,
468 ...)
469 {
470 va_list args;
471 va_start(args, fmt);
472 vprintf_helper("ELC", ANSI_FG_YELLOW, "INF", ANSI_BG_WHITE, fmt, args);
473 va_end(args);
474 }
475
482 const F_char *fmt,
483 ...)
484 {
485 va_list args;
486 va_start(args, fmt);
487 vprintf_helper("ELC", ANSI_FG_YELLOW, "WRN", ANSI_BG_ORANGE, fmt, args);
488 va_end(args);
489 }
490
497 const F_char *fmt,
498 ...)
499 {
500 va_list args;
501 va_start(args, fmt);
502 vprintf_helper("ELC", ANSI_FG_YELLOW, "ERR", ANSI_BG_RED, fmt, args);
503 va_end(args);
504 }
505
512 const F_char *fmt,
513 ...)
514 {
515 va_list args;
516 va_start(args, fmt);
517 vprintf_helper("ELC", ANSI_FG_YELLOW, "FTL", ANSI_BG_MAGENTA, fmt, args);
518 va_end(args);
519 }
520
527 const F_char *fmt,
528 ...)
529 {
530 va_list args;
531 va_start(args, fmt);
532 vprintf_helper("ENG", ANSI_FG_BLUE, "INF", ANSI_BG_WHITE, fmt, args);
533 va_end(args);
534 }
535
542 const std::string& name)
543 {
544 printf("ENG", ANSI_FG_BLUE, "SES", ANSI_BG_WHITE, name.c_str());
545 }
546
552 const std::string& message)
553 {
554 printf("ENG", ANSI_FG_BLUE, "INF", ANSI_BG_WHITE, message.c_str());
555 }
556
563 const F_char *fmt,
564 ...)
565 {
566 va_list args;
567 va_start(args, fmt);
568 vprintf_helper("ENG", ANSI_FG_BLUE, "WRN", ANSI_BG_ORANGE, fmt, args);
569 va_end(args);
570 }
571
578 const F_char *fmt,
579 ...)
580 {
581 va_list args;
582 va_start(args, fmt);
583 vprintf_helper("ENG", ANSI_FG_BLUE, "ERR", ANSI_BG_RED, fmt, args);
584 va_end(args);
585 }
586
593 const F_char *fmt,
594 ...)
595 {
596 va_list args;
597 va_start(args, fmt);
598 vprintf_helper("ENG", ANSI_FG_BLUE, "FTL", ANSI_BG_MAGENTA, fmt, args);
599 va_end(args);
600 }
601 }
602}
603
608#define ERR(func) \
609 do \
610 { \
611 F_err _err = (func); \
612 if (_err != fray::errors::NONE) \
613 { \
614 fray::log::engineError(fray::errors::description(_err)); \
615 return _err; \
616 } \
617 } while (0)
618
623#define ERR2(func) \
624 do \
625 { \
626 F_err _err = (func); \
627 if (_err != fray::errors::NONE) \
628 { \
629 fray::log::engineWarn("%s", fray::errors::description(_err)); \
630 } \
631 } while (0)
632
633#endif
~ConsoleSuppression()
Restores the previous Console visibility.
ConsoleSuppression(const ConsoleSuppression &)=delete
ConsoleSuppression & operator=(const ConsoleSuppression &)=delete
ConsoleSuppression()
Suppresses Console delivery on the calling thread.
ProjectScope(const std::string &project)
Save the calling thread's tag and optionally replace it.
std::string _previous
Project tag to restore when this scope ends.
~ProjectScope()
Restore the saved tag on the calling thread.
ProjectScope & operator=(const ProjectScope &)=delete
Disallow copy assignment of a project tag scope.
ProjectScope(const ProjectScope &)=delete
Disallow copying a project tag scope.
SinkSuppression & operator=(const SinkSuppression &)=delete
Disallow copy assignment of a suppression scope.
bool _previous
Setting to restore when this scope ends.
SinkSuppression()
Suppresses the sink on the calling thread.
SinkSuppression(const SinkSuppression &)=delete
Disallow copying a suppression scope.
~SinkSuppression()
Restores the previous setting on the calling thread.
bool & consoleVisible()
Whether the calling thread's log entries may be shown in the Console.
std::string & threadProject()
Return the calling thread's project tag; an empty tag denotes the application.
F_void engineInfo(const F_char *fmt,...)
Log info for Engine.
constexpr F_long DATE_SIZE
Date buffer size.
F_void engineError(const F_char *fmt,...)
Log error for Engine.
F_void engineWarn(const F_char *fmt,...)
Log warning for Engine.
constexpr const F_char * ANSI_FG_WHITE
ANSI FG white.
F_long threadId()
Small sequential id for the calling thread, assigned on its first call (the first caller is 0).
constexpr const F_char * ANSI_BG_YELLOW
ANSI BG yellow.
constexpr const F_char * ANSI_INVERSE
ANSI inverse.
constexpr const F_char * ANSI_FG_MAGENTA
ANSI FG magenta.
std::mutex & sinkMutex()
Return the mutex protecting access to the shared sink slot.
constexpr const F_char * ANSI_FG_ORANGE
ANSI FG orange (256-color).
F_void setSink(Sink sink)
Replace the sink; an empty function removes it. Locks sinkMutex; an in-flight logging call may still ...
F_void electronError(const F_char *fmt,...)
Log error for Electron.
F_char[TIME_SIZE] timeBuffer
Time buffer type.
bool & sinkSuppressed()
Whether the calling thread's printed lines skip the sink, so they reach stdout only.
constexpr F_long TIME_SIZE
Time buffer size.
constexpr const F_char * ANSI_BG_BLACK
ANSI BG black.
F_void getDate(F_char *date)
Write "YY.MM.DD" into buffer.
constexpr const F_char * ANSI_BG_MAGENTA
ANSI BG magenta.
constexpr const F_char * ANSI_BG_GREEN
ANSI BG green.
F_void engineFatal(const F_char *fmt,...)
Log fatal for Engine.
constexpr const F_char * ANSI_BG_WHITE
ANSI BG white.
F_void electronWarn(const F_char *fmt,...)
Log warning for Electron.
constexpr const F_char * ANSI_BG_CYAN
ANSI BG cyan.
constexpr const F_char * ANSI_BG_BLUE
ANSI BG blue.
constexpr const F_char * ANSI_FG_BLUE
ANSI FG blue.
constexpr const F_char * ANSI_BG_RED
ANSI BG red.
F_void engineSession(const std::string &name)
Marks the start of a log session under the calling thread's project tag. The Engine records it as a s...
constexpr const F_char * ANSI_BG_ORANGE
ANSI BG orange (256-color).
constexpr const F_char * ANSI_FG_CYAN
ANSI FG cyan.
constexpr const F_char * ANSI_RESET
ANSI reset code.
F_char[DATE_SIZE] dateBuffer
Date buffer type.
F_void printf(const F_char *PID, const F_char *PIDColor, const F_char *level, const F_char *levelColor, const F_char *message)
Print a formatted log line with PID, level and colors. Serializes and flushes stdout,...
constexpr const F_char * ANSI_FG_GREEN
ANSI FG green.
constexpr const F_char * ANSI_UNDERLINE
ANSI underline.
F_void vprintf_helper(const F_char *PID, const F_char *PIDColor, const F_char *level, const F_char *levelColor, const F_char *fmt, va_list args)
Format up to 1023 message bytes and delegate to printf().
F_void generateTimestamp(F_char *timestamp, std::chrono::system_clock::time_point now=std::chrono::system_clock::now())
Write "[HH:MM:SS:mmm] [YY.MM.DD]" into buffer.
std::shared_ptr< Sink > & sinkSlot()
Return the shared sink slot; callers must hold sinkMutex when accessing it.
constexpr const F_char * ANSI_BLINK
ANSI blink.
F_void electronInfo(const F_char *fmt,...)
Log info for Electron.
constexpr const F_char * ANSI_FG_BLACK
ANSI FG black.
constexpr const F_char * ANSI_FG_YELLOW
ANSI FG yellow.
F_void getTime(F_char *time, std::chrono::system_clock::time_point now=std::chrono::system_clock::now())
Write "HH:MM:SS.mmm" into buffer.
F_void electronFatal(const F_char *fmt,...)
Log fatal for Electron.
constexpr F_long TIMESTAMP_SIZE
Timestamp buffer size.
std::function< void(const F_char *PID, const F_char *level, F_long thread, const std::string &project, const F_char *message, bool consoleVisible)> Sink
Receives each printed line synchronously on the logging thread; it must not log. The sink runs withou...
constexpr const F_char * ANSI_FG_RED
ANSI FG red.
F_char[TIMESTAMP_SIZE] TimestampBuffer
Timestamp buffer type.
constexpr const F_char * ANSI_BOLD
ANSI bold.
int32_t F_long
Signed 32-bit integer (also the base of F_err).
Definition types.hpp:32
void F_void
Alias for void.
Definition types.hpp:20
char F_char
Alias for char.
Definition types.hpp:24