-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSmallBetterLogger.hpp
1769 lines (1463 loc) · 63.4 KB
/
SmallBetterLogger.hpp
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
MIT License
Copyright (c) 2019 Filip Dutescu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef SMALL_BETTER_LOGGER_H
#define SMALL_BETTER_LOGGER_H
// Log Levels macros to be used with "SBLOGGER_LOG_LEVEL" macro for defining a default level
#define SBLOGGER_LEVEL_TRACE 0
#define SBLOGGER_LEVEL_DEBUG 1
#define SBLOGGER_LEVEL_INFO 2
#define SBLOGGER_LEVEL_WARN 3
#define SBLOGGER_LEVEL_ERROR 4
#define SBLOGGER_LEVEL_CRITICAL 5
#define SBLOGGER_LEVEL_OFF 6
//
// Define your preferred active level (e.g. using the macro bellow), or use the static method Logger::SetLoggingLevel(const LOG_LEVELS& level)
//
//#define SBLOGGER_LOG_LEVEL SBLOGGER_LEVEL_TRACE
//
// Either uncomment or define this macro, should your environment support colours and you wish to use them
//
//#define SBLOGGER_COLOURS
// Detect the standard used and set the appropriate macros
#if __cplusplus != 199711L
#if __cplusplus < 201703L
// For pre C++17 compilers define the "SBLOGGER_LEGACY" macro, to replace <filesystem> operations with regex and other alternatives
#define SBLOGGER_LEGACY
#endif
#if __cplusplus <= 201703L
// For formatting dates to string pre C++20
#define SBLOGGER_OLD_DATES
#endif
#endif
// Detect OS and set the appropriate macros
#if macintosh || Macintos
#define SBLOGGER_OS9
#elif !_WIN32
#define SBLOGGER_NIX
#endif
// Cross-platform newline macros
#ifdef SBLOGGER_NIX
#define SBLOGGER_PATH_SEPARATOR '/'
#elif SBLOGGER_OS9
#define SBLOGGER_PATH_SEPARATOR '/'
#else
#define SBLOGGER_PATH_SEPARATOR '\\'
#endif
#ifdef SBLOGGER_LEGACY
// Raw file path regex as string literal
#define SBLOGGER_RAW_FILE_PATH_REGEX R"regex(^(((([a-zA-Z]\:|\\)+\\[^\/\\:"'*?<>|\0]+)+|([^\/\\:"'*?<>|\0]+)+)|(((\.\/|\~\/|\/[^\/\\:"'*?~<>|\0]+\/)?[^\/\\:"'*?~<>|\0]+)+))$)regex"
#endif
// Used for writing to output stream
#include <iostream>
#include <fstream>
// Used for formatting and creating the output string
#include <sstream>
#include <vector>
// Used for modf function
#include <cmath>
// Used for str* functions
#include <cstring>
// Used for processing using time such as timed file logs and date formatting (if SBLOGGER_LEGACY is not defined)
#include <chrono>
// Used for asynchronous operations such as changing files for timed file logs
#include <thread>
#include <mutex>
// For pre C++17 compilers define the "SBLOGGER_LEGACY" macro, to replace <filesystem> operations with regex and other alternatives
#ifdef SBLOGGER_LEGACY
// Used for file path checking
#include <regex>
#else
// Used for file path checking and file manipulation
#include <filesystem>
#endif
// For formatting dates to string pre C++20
#ifdef SBLOGGER_OLD_DATES
// Make use of std::strftime
#include <ctime>
#endif
// For pre C++17 compilers define the "LEGACY" macro, to replace <filesystem> operations with regex and other alternatives
#ifdef SBLOGGER_LEGACY
// File Path Regex using std::regex
#define SBLOGGER_FILE_PATH_REGEX std::regex(SBLOGGER_RAW_FILE_PATH_REGEX)
#endif
namespace sblogger
{
//
// Loggers' declaration
//
// Basic Logger
// Abstract class which implements basic logger methods and members (ex.: auto flush, format, replace formatters etc)
class Logger;
using logger = Logger;
// Stream Logger
// Used to log messages to a non-file stream (ex.: STDOUT, STDERR, STDLOG)
class StreamLogger;
using stream_logger = StreamLogger;
// File Logger
// Used to log messages to a file stream
class FileLogger;
using file_logger = FileLogger;
// Daily Logger
// Used to log messages to a file stream, recreated daily at a specified time point
class DailyLogger;
using daily_logger = DailyLogger;
//
// Custom exceptions' definition
//
// Base exception
class SBLoggerException;
using sblogger_exception = SBLoggerException;
// NullOrEmptyPathException
// Thrown when the given file path is null or empty
class NullOrEmptyPathException;
using null_or_empty_path_exception = NullOrEmptyPathException;
// NullOrWhitespaceNameException
// Thrown when the given file name is null or whitespace
class NullOrWhitespaceNameException;
using null_or_whitespace_name_exception = NullOrWhitespaceNameException;
// InvalidFilePathException
// Thrown when the specified file could not be opened
class InvalidFilePathException;
using invalid_file_path_exception = InvalidFilePathException;
// TimeRangeException
// Thrown when a time related value is out of bounds (e.g.: hours not in [0, 23])
class TimeRangeException;
using time_range_exception = TimeRangeException;
//
// Enum definitions
//
// Log level enum. Contains all possible log levels, such as TRACE, ERROR, FATAL etc.
enum class LogLevel
{
TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL, OFF
};
using log_levels = LogLevel;
// Stream types to be used by a Logger instance
enum class StreamType
{
STDOUT, STDERR, STDLOG
};
using stream_type = StreamType;
//
// Custom exceptions
//
// Base exception
class SBLoggerException : public std::exception
{
protected:
//
// Protected members
//
std::string m_Exception;
//
// Protected methods
//
// Creates an exception with a given message
SBLoggerException(const std::string& exception);
// Creates an exception with a given message
SBLoggerException(const char* exception);
public:
// Throw exception
~SBLoggerException() throw() = default;
// Get error message
const char* What() const noexcept;
// Get error message
virtual const char* what() const noexcept;
};
//
// Constructors and destructors
//
// Creates an exception with a given message
SBLoggerException::SBLoggerException(const std::string& exception)
: std::exception(), m_Exception(exception)
{ }
// Creates an exception with a given message
SBLoggerException::SBLoggerException(const char* exception)
: std::exception(), m_Exception(exception)
{ }
//
// Public methods
//
// Get error message
inline const char* SBLoggerException::What() const noexcept { return m_Exception.c_str(); }
// Get error message
inline const char* SBLoggerException::what() const noexcept { return m_Exception.c_str(); }
//
// NullOrEmptyPathException
//
// Thrown when the given file path is null or empty
class NullOrEmptyPathException : public SBLoggerException
{
public:
// Default constructor
NullOrEmptyPathException();
};
// Default constructor
NullOrEmptyPathException::NullOrEmptyPathException()
: SBLoggerException("File path cannot be null or empty.")
{ }
//
// NullOrWhitespaceNameException
//
// Thrown when the given file name is null or whitespace
class NullOrWhitespaceNameException : public SBLoggerException
{
public:
// Default constructor
NullOrWhitespaceNameException();
};
// Default constructor
NullOrWhitespaceNameException::NullOrWhitespaceNameException()
: SBLoggerException("File name cannot be null or whitespace.")
{ }
//
// InvalidFilePathException
//
// Thrown when the specified file could not be opened
class InvalidFilePathException : public SBLoggerException
{
public:
//
// Constructors and destructors
//
// Default constructor
InvalidFilePathException();
// Creates an invalid file path exception with a given message
InvalidFilePathException(const std::string& filePath);
};
//
// Constructors and destructors
//
// Default constructor
InvalidFilePathException::InvalidFilePathException()
: SBLoggerException("Cannot open log file to write to.")
{ }
// Creates an invalid file path exception with a given message
InvalidFilePathException::InvalidFilePathException(const std::string& filePath)
: SBLoggerException("Cannot open log file " + filePath + '.')
{ }
//
// TimeRangeException
//
// Thrown when a time related value is out of bounds (e.g.: hours not in [0, 23])
class TimeRangeException : public SBLoggerException
{
public:
//
// Constructors and destructors
//
// Default constructor
TimeRangeException();
};
//
// Constructors and destructors
//
// Default constructor
TimeRangeException::TimeRangeException()
: SBLoggerException("Time value not in the allowed interval.")
{ }
//
// Classes' definitions
//
// Abstract class which implements basic logger methods and members (ex.: auto flush, format, replace formatters etc)
class Logger
{
protected:
//
// Protected members
//
std::string m_Format;
bool m_AutoFlush;
size_t m_IndentCount;
static LogLevel s_CurrentLogLevel;
//
// Protected constructors
//
// Initialize a logger, with a format, auto flush (by default)
Logger(const std::string& format, bool autoFlush);
// Initialize a logger, with no format, auto flush (by default)
Logger(bool autoFlush) noexcept;
// Copy constructor
Logger(const Logger& other) noexcept;
//
// Protected methods
//
// Writes string to appropriate stream
virtual void writeToStream(const std::string& message) = 0;
// Converts a T value to a string to be used in writing a log
template<typename T>
std::string stringConvert(const T& t) const noexcept;
// Adds ANSII colour codes if current stream supports them
// (The Logger base class does not do anything with the message, the method needing implementation from derived classes)
virtual void addColours(std::string& message) const noexcept;
// Add indent to string (if it is set)
void addIndent(std::string& message) const noexcept;
// Add padding to string (if padding format exists)
void addPadding(std::string& message) const noexcept;
// Append format (if it exists) and replace all "{n}" placeholders with their respective values (n=0,...)
std::string replacePlaceholders(std::string message, const std::vector<std::string>& items) const noexcept;
// Replaces predefined placeholders from the message (e.g. "%er" will be changed to "Error" in the final message)
void replacePredefinedPlaceholders(std::string& message) const noexcept;
// Replace current logging level in format
void replaceCurrentLevel(std::string& message) const noexcept;
// Replace other placeholders, such as those for file, line and function related information
void replaceOthers(std::string& message, const char* file, const char* line, const char* function) const noexcept;
// Replace date format using std::strftime (pre C++20) or std::chrono::format
void replaceDateFormats(std::string& message) const noexcept;
public:
// Default destructor
virtual ~Logger() = default;
//
// Public methods
//
// Set the current logging level to one of the "LOG_LEVELS" options (ex.: TRACE, DEBUG, INFO etc).
static void SetLoggingLevel(const LogLevel& level) noexcept;
// Get the current logging level (one of the "LOG_LEVELS" options, ex.: TRACE, DEBUG, INFO etc).
static LogLevel GetLoggingLevel() noexcept;
// Get the current log format
inline std::string GetFormat() const noexcept;
// Set the current log format to "format"
inline void SetFormat(const std::string& format);
// Flush appropriate stream
virtual void Flush() noexcept = 0;
// Indent (prepend '\t') log, returns the number of indents the final message will contain
virtual size_t Indent() noexcept;
// Dedent (remove '\t') log, returns the number of indents the final message will contain
virtual size_t Dedent() noexcept;
//
// Generic Methods: Write a TRACE level message (depending on the specified "LOG_LEVEL") to a stream
//
// Writes to the stream the newline character, assuming a default log level of TRACE
void WriteLine(LogLevel logLevel = LogLevel::TRACE);
// Writes to the stream a message and inserts values into placeholders (should they exist), assuming a default log level of TRACE
template<typename ...T>
void Write(const std::string& message, const T& ...t);
// Writes to the stream a message and inserts values into placeholders (should they exist) and finishes with the newline character, assuming a default log level of TRACE
template<typename ...T>
void WriteLine(const std::string& message, const T& ...t);
//
// Generic Methods: Write a level message (depending on the specified "LOG_LEVEL") to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of "logLevel" importance
template<typename ...T>
void Write(LogLevel logLevel, const std::string& message, const T& ...t);
// Writes to the stream a message and inserts values into placeholders (should they exist) and finishes with the newline character, of "logLevel" importance
template<typename ...T>
void WriteLine(LogLevel logLevel, const std::string& message, const T& ...t);
//
// Generic Methods: Write a TRACE level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of TRACE importance
template<typename ...T>
void Trace(const std::string& message, const T& ...t);
//
// Generic Methods: Write a DEBUG level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of DEBUG importance
template<typename ...T>
void Debug(const std::string& message, const T& ...t);
//
// Generic Methods: Write a INFO level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of INFO importance
template<typename ...T>
void Info(const std::string& message, const T& ...t);
//
// Generic Methods: Write a WARN level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of WARN importance
template<typename ...T>
void Warn(const std::string& message, const T& ...t);
//
// Generic Methods: Write a ERROR level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of ERROR importance
template<typename ...T>
void Error(const std::string& message, const T& ...t);
//
// Generic Methods: Write a CRITICAL level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of CRITICAL importance
template<typename ...T>
void Critical(const std::string& message, const T& ...t);
};
// Static member initialization
// Check to see what is the current active log level, by default use TRACE
#if SBLOGGER_LOG_LEVEL == SBLOGGER_LEVEL_DEBUG
LOG_LEVELS Logger::s_CurrentLogLevel = LOG_LEVELS::DEBUG;
#elif SBLOGGER_LOG_LEVEL == SBLOGGER_LEVEL_INFO
LOG_LEVELS Logger::s_CurrentLogLevel = LOG_LEVELS::INFO;
#elif SBLOGGER_LOG_LEVEL == SBLOGGER_LEVEL_WARN
LOG_LEVELS Logger::s_CurrentLogLevel = LOG_LEVELS::WARN;
#elif SBLOGGER_LOG_LEVEL == SBLOGGER_LEVEL_ERROR
LOG_LEVELS Logger::s_CurrentLogLevel = LOG_LEVELS::ERROR;
#elif SBLOGGER_LOG_LEVEL == SBLOGGER_LEVEL_CRITICAL
LOG_LEVELS Logger::s_CurrentLogLevel = LOG_LEVELS::CRITICAL;
#elif SBLOGGER_LOG_LEVEL == SBLOGGER_LEVEL_OFF
LOG_LEVELS Logger::s_CurrentLogLevel = LOG_LEVELS::OFF;
#else
LogLevel Logger::s_CurrentLogLevel = LogLevel::TRACE;
#endif
//
// Protected constructors
//
// Initialize a logger, with a format, auto flush (by default)
inline Logger::Logger(const std::string& format, bool autoFlush)
: m_Format(format), m_AutoFlush(autoFlush), m_IndentCount(0u)
{
if (!m_Format.empty())
{
addPadding(m_Format);
#ifdef SBLOGGER_LEGACY
std::string placeholder = "tr";
#else
std::string_view placeholder = "tr";
#endif
size_t placeholderPosition;
while ((placeholderPosition = m_Format.find(placeholder)) != std::string::npos && (m_Format[placeholderPosition - 1u] == '%' || m_Format[placeholderPosition - 2u] == '%'))
m_Format[placeholderPosition - 1u] == '^' ? m_Format.replace(placeholderPosition - 2u, placeholder.size() + 2u, "TRACE") : m_Format.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Trace");
placeholder = "dbg";
while ((placeholderPosition = m_Format.find(placeholder)) != std::string::npos && (m_Format[placeholderPosition - 1u] == '%' || m_Format[placeholderPosition - 2u] == '%'))
m_Format[placeholderPosition - 1u] == '^' ? m_Format.replace(placeholderPosition - 2u, placeholder.size() + 2u, "DEBUG") : m_Format.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Debug");
placeholder = "inf";
while ((placeholderPosition = m_Format.find(placeholder)) != std::string::npos && (m_Format[placeholderPosition - 1u] == '%' || m_Format[placeholderPosition - 2u] == '%'))
m_Format[placeholderPosition - 1u] == '^' ? m_Format.replace(placeholderPosition - 2u, placeholder.size() + 2u, "INFO") : m_Format.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Info");
placeholder = "wn";
while ((placeholderPosition = m_Format.find(placeholder)) != std::string::npos && (m_Format[placeholderPosition - 1u] == '%' || m_Format[placeholderPosition - 2u] == '%'))
m_Format[placeholderPosition - 1u] == '^' ? m_Format.replace(placeholderPosition - 2u, placeholder.size() + 2u, "WARN") : m_Format.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Warn");
placeholder = "er";
while ((placeholderPosition = m_Format.find(placeholder)) != std::string::npos && (m_Format[placeholderPosition - 1u] == '%' || m_Format[placeholderPosition - 2u] == '%'))
m_Format[placeholderPosition - 1u] == '^' ? m_Format.replace(placeholderPosition - 2u, placeholder.size() + 2u, "ERROR") : m_Format.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Error");
placeholder = "crt";
while ((placeholderPosition = m_Format.find(placeholder)) != std::string::npos && (m_Format[placeholderPosition - 1u] == '%' || m_Format[placeholderPosition - 2u] == '%'))
m_Format[placeholderPosition - 1u] == '^' ? m_Format.replace(placeholderPosition - 2u, placeholder.size() + 2u, "CRITICAL") : m_Format.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Critical");
}
}
// Initialize a logger, with no format, auto flush (by default)
inline Logger::Logger(bool autoFlush) noexcept
: m_Format(), m_AutoFlush(autoFlush), m_IndentCount(0u)
{ }
// Copy constructor
inline Logger::Logger(const Logger& other) noexcept
: m_Format(other.m_Format), m_AutoFlush(other.m_AutoFlush), m_IndentCount(other.m_IndentCount)
{ }
//
// Protected methods
//
// Converts a T value to a string to be used in writing a log
template<typename T>
inline std::string Logger::stringConvert(const T& t) const noexcept
{
std::stringstream ss;
ss << t;
return ss.str();
}
// Adds ANSII colour codes if current stream supports them
// (The Logger base class does not do anything with the message, the method needing implementation from derived classes)
inline void Logger::addColours(std::string& message) const noexcept
{
char colours[][12]{ { "reset" }, { "black" }, { "red" }, { "green" }, { "yellow" }, { "blue" }, { "magenta" }, { "cyan" }, { "white" },
{ "bg-black" }, { "bg-red" }, { "bg-green" }, { "bg-yellow" }, { "bg-blue" }, { "bg-magenta" }, { "bg-cyan" }, { "bg-white" } };
size_t placeholderPosition, placeholderSize;
char currentColour[17]{ '{' };
for (size_t i = 0u; i < 17u; ++i)
if ((placeholderPosition = message.find(colours[i])) != std::string::npos
&& placeholderPosition > 1u && message[placeholderPosition - 1u] == '{'
&& placeholderPosition < (message.size() - 1u) && message[placeholderPosition + std::strlen(colours[i])] == '}')
{
std::strncpy(currentColour + 1, colours[i], std::strlen(colours[i]) + 1u);
std::strncat(currentColour, "}", 1u);
while ((placeholderPosition = message.find(currentColour)) != std::string::npos)
{
placeholderSize = std::strlen(currentColour);
message[placeholderPosition - 1u] == '^' ?
message.replace(placeholderPosition - 2u, placeholderSize + 2u, "")
: message.replace(placeholderPosition - 1u, placeholderSize + 1u, "");
}
}
}
// Add indent to string (if it is set)
inline void Logger::addIndent(std::string& message) const noexcept
{
for (size_t i = 0u; i < m_IndentCount; ++i)
message = '\t' + message;
}
// Add padding to string (if padding format exists)
inline void Logger::addPadding(std::string& message) const noexcept
{
#ifdef SBLOGGER_LEGACY
std::string placeholders[] { "msg", "lvl", "tr", "dbg", "inf", "wn", "er", "crt" };
#else
std::string_view placeholders[] { "msg", "lvl", "tr", "dbg", "inf", "wn", "er", "crt" };
#endif
std::string digits = "1234567890", floatDigits = "1234567890.", currentPadding;
size_t placeholderPosition, offset = 0u, noDigits, noDecimals, currentSectionEnd, placeholderSize, noPlaceholders = 8u;
float noSpacesLeft, noSpacesRight;
char nextCharacter;
while ((placeholderPosition = message.find_first_of(digits, offset)) != std::string::npos)
{
if (message[placeholderPosition - 1u] != '%' && (placeholderPosition > 1u && message[placeholderPosition - 2u] != '%' && message[placeholderPosition - 1u] != '.'))
offset += placeholderPosition + 1u;
else
{
if(message[placeholderPosition - 1u] != '%')
currentPadding = message.substr(placeholderPosition - 1u, message.find_first_not_of(floatDigits, placeholderPosition + 1u) - placeholderPosition + 1u);
else
currentPadding = message.substr(placeholderPosition, message.find_first_not_of(floatDigits, placeholderPosition) - placeholderPosition);
noDigits = currentPadding.size();
noDecimals = (noDecimals = currentPadding.find('.')) != std::string::npos ? (noDigits - noDecimals - 1u) : 0u;
noSpacesRight = std::modf(std::stof(currentPadding), &noSpacesLeft);
for (size_t i = 0u; i < noDecimals; ++i)
noSpacesRight *= 10;
placeholderSize = 0u;
for (size_t i = 0u; i < noPlaceholders && !placeholderSize; ++i)
if ((currentSectionEnd = message.find(placeholders[i], placeholderPosition + noDigits)) != std::string::npos && placeholderPosition + noDigits == currentSectionEnd - 1u)
placeholderSize = placeholders[i].size();
if (noSpacesRight && (placeholderSize || (currentSectionEnd = message.find_first_of(" .-,@#(){}[]'\"\\/!`~|;:?><=+-_%&*", placeholderPosition + noDigits + 1u)) != std::string::npos))
{
nextCharacter = message[placeholderSize ? (currentSectionEnd + placeholderSize) : currentSectionEnd];
message.replace(placeholderSize ? (currentSectionEnd + placeholderSize) : currentSectionEnd, 1u, (size_t)noSpacesRight + 1u, ' ');
if(nextCharacter != ' ')
message[placeholderSize ? (currentSectionEnd + placeholderSize) : (currentSectionEnd + (size_t)noSpacesRight)] = nextCharacter;
}
message.replace(placeholderPosition - 1u, noDigits + 1u, !placeholderSize ? (size_t)noSpacesLeft : ((size_t)noSpacesLeft + 1u) , ' ');
if (placeholderSize)
message[placeholderPosition + (size_t)noSpacesLeft] = '%';
}
}
}
// Append format (if it exists) and replace all "{n}" placeholders with their respective values (n=0,...)
inline std::string Logger::replacePlaceholders(std::string message, const std::vector<std::string>& items) const noexcept
{
bool hasMacros = false;
std::string placeholder;
size_t placeholderPosition, placeholderSize, noArguments = items.size();
if(noArguments > 3u)
for (size_t i = noArguments - 1u; i >= 0u && !hasMacros; --i)
if (items[i] == "__MACROS__")
hasMacros = true;
for (size_t i = 0u; i < noArguments; ++i)
{
placeholderSize = (placeholder = '{' + std::to_string(i) + '}').size();
while ((placeholderPosition = message.find(placeholder)) != std::string::npos)
message.replace(placeholderPosition, placeholderSize, items[i]);
}
if(!m_Format.empty())
message = (placeholderPosition = m_Format.find("%msg")) != std::string::npos ? std::string(m_Format).replace(placeholderPosition, 4u, message) : (m_Format + ' ' + message);
addIndent(message);
addPadding(message);
addColours(message);
replacePredefinedPlaceholders(message);
replaceCurrentLevel(message);
if(hasMacros)
replaceOthers(message, items[noArguments - 3u].c_str(), items[noArguments - 2u].c_str(), items[noArguments - 1u].c_str());
else
replaceOthers(message, nullptr, nullptr, nullptr);
replaceDateFormats(message);
return message;
}
// Replaces predefined placeholders from the message (e.g. "%er" will be changed to "Error" in the final message)
inline void Logger::replacePredefinedPlaceholders(std::string& message) const noexcept
{
#ifdef SBLOGGER_LEGACY
std::string placeholder = "tr";
#else
std::string_view placeholder = "tr";
#endif
size_t placeholderPosition;
while ((placeholderPosition = message.find(placeholder)) != std::string::npos && (message[placeholderPosition - 1u] == '%' || message[placeholderPosition - 2u] == '%'))
message[placeholderPosition - 1u] == '^' ? message.replace(placeholderPosition - 2u, placeholder.size() + 2u, "TRACE") : message.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Trace");
while ((placeholderPosition = message.find(placeholder = "dbg")) != std::string::npos && (message[placeholderPosition - 1u] == '%' || message[placeholderPosition - 2u] == '%'))
message[placeholderPosition - 1u] == '^' ? message.replace(placeholderPosition - 2u, placeholder.size() + 2u, "DEBUG") : message.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Debug");
while ((placeholderPosition = message.find(placeholder = "inf")) != std::string::npos && (message[placeholderPosition - 1u] == '%' || message[placeholderPosition - 2u] == '%'))
message[placeholderPosition - 1u] == '^' ? message.replace(placeholderPosition - 2u, placeholder.size() + 2u, "INFO") : message.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Info");
while ((placeholderPosition = message.find(placeholder = "wn")) != std::string::npos && (message[placeholderPosition - 1u] == '%' || message[placeholderPosition - 2u] == '%'))
message[placeholderPosition - 1u] == '^' ? message.replace(placeholderPosition - 2u, placeholder.size() + 2u, "WARN") : message.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Warn");
while ((placeholderPosition = message.find(placeholder = "er")) != std::string::npos && (message[placeholderPosition - 1u] == '%' || message[placeholderPosition - 2u] == '%'))
message[placeholderPosition - 1u] == '^' ? message.replace(placeholderPosition - 2u, placeholder.size() + 2u, "ERROR") : message.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Error");
while ((placeholderPosition = message.find(placeholder = "crt")) != std::string::npos && (message[placeholderPosition - 1u] == '%' || message[placeholderPosition - 2u] == '%'))
message[placeholderPosition - 1u] == '^' ? message.replace(placeholderPosition - 2u, placeholder.size() + 2u, "CRITICAL") : message.replace(placeholderPosition - 1u, placeholder.size() + 2u, "Critical");
}
// Replace current logging level in format
inline void Logger::replaceCurrentLevel(std::string& message) const noexcept
{
const size_t placeholderPosition = message.find("lvl");
if (placeholderPosition != std::string::npos && (message[placeholderPosition - 1u] == '%' || message[placeholderPosition - 2u] == '%'))
switch (s_CurrentLogLevel)
{
case LogLevel::TRACE:
message[placeholderPosition - 1u] == '^' ?
message.replace(placeholderPosition - 2u, 5u, "TRACE") : message.replace(placeholderPosition - 2u, 4u, "Trace");
break;
case LogLevel::DEBUG:
message[placeholderPosition - 1u] == '^' ?
message.replace(placeholderPosition - 2u, 5u, "DEBUG") : message.replace(placeholderPosition - 2u, 4u, "Debug");
break;
case LogLevel::INFO:
message[placeholderPosition - 1u] == '^' ?
message.replace(placeholderPosition - 2u, 5u, "INFO") : message.replace(placeholderPosition - 2u, 4u, "Info");
break;
case LogLevel::WARN:
message[placeholderPosition - 1u] == '^' ?
message.replace(placeholderPosition - 2u, 5u, "WARN") : message.replace(placeholderPosition - 2u, 4u, "Warn");
break;
case LogLevel::ERROR:
message[placeholderPosition - 1u] == '^' ?
message.replace(placeholderPosition - 2u, 5u, "ERROR") : message.replace(placeholderPosition - 2u, 4u, "Error");
break;
case LogLevel::CRITICAL:
message[placeholderPosition - 1u] == '^' ?
message.replace(placeholderPosition - 2u, 5u, "CRITICAL") : message.replace(placeholderPosition - 2u, 4u, "Critical");
break;
default:
message = "";
break;
}
}
// Replace other placeholders, such as those for file, line and function related information
inline void Logger::replaceOthers(std::string& message, const char* file, const char* line, const char* function) const noexcept
{
#ifdef SBLOGGER_LEGACY
std::string placeholder = "src";
#else
std::string_view placeholder = "src";
#endif
size_t placeholderPosition = message.find(placeholder);
char* fileShortName;
while (placeholderPosition != std::string::npos && message[placeholderPosition - 1u] == '%')
message.replace(placeholderPosition - 1u, 4u, file == nullptr ? "" :
((fileShortName = (char*)std::strrchr(file, SBLOGGER_PATH_SEPARATOR)) ? (fileShortName + 1) : ""));
placeholder = "fsrc";
while ((placeholderPosition = message.find(placeholder)) != std::string::npos && message[placeholderPosition - 1u] == '%')
message.replace(placeholderPosition - 1u, 5u, file == nullptr ? "" : file);
placeholder = "ln";
while ((placeholderPosition = message.find(placeholder)) != std::string::npos && message[placeholderPosition - 1u] == '%')
message.replace(placeholderPosition - 1u, 3u, line == nullptr ? "" : line);
placeholder = "func";
while ((placeholderPosition = message.find(placeholder)) != std::string::npos && message[placeholderPosition - 1u] == '%')
message.replace(placeholderPosition - 1u, 5u, function == nullptr ? "" : function);
}
// Replace date format using std::strftime (pre C++20) or std::chrono::format
inline void Logger::replaceDateFormats(std::string& message) const noexcept
{
// Replace date format using std::strftime (pre C++20)
#ifdef SBLOGGER_OLD_DATES
std::time_t currentTime = std::time(nullptr);
size_t messageLength = message.size();
char* buffer = new char[messageLength + 101u]{ 0 };
if (std::strftime(buffer, sizeof(char) * (messageLength + 100u), message.c_str(), std::localtime(¤tTime)))
message = std::string(buffer);
delete[] buffer;
// Replace date format using std::chrono::format
#else
// Replace date format using std::chrono::format
// Wait for MSVC to catch up
#endif
}
//
// Public methods
//
// Indent (prepend '\t') log, returns the number of indents the final message will contain
inline size_t Logger::Indent() noexcept
{
return ++m_IndentCount;
}
// Dedent (prepend '\t') log, returns the number of indents the final message will contain
inline size_t Logger::Dedent() noexcept
{
return m_IndentCount > 0 ? --m_IndentCount : m_IndentCount;
}
// Set the current logging level to one of the "LOG_LEVELS" options (ex.: TRACE, DEBUG, INFO etc).
inline void Logger::SetLoggingLevel(const LogLevel& level) noexcept
{
s_CurrentLogLevel = level;
}
// Get the current logging level (one of the "LOG_LEVELS" options, ex.: TRACE, DEBUG, INFO etc).
inline LogLevel Logger::GetLoggingLevel() noexcept
{
return s_CurrentLogLevel;
}
// Get the current log format
inline std::string Logger::GetFormat() const noexcept
{
return m_Format;
}
// Set the current log format to "format"
inline void Logger::SetFormat(const std::string& format)
{
m_Format = format;
}
// Writes to the stream the newline character with a log level of TRACE
inline void Logger::WriteLine(LogLevel logLevel)
{
if(s_CurrentLogLevel <= logLevel)
writeToStream("\n");
}
//
// Generic write methods to write a TRACE level message to the stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist) with a default level of TRACE
template<typename ...T>
inline void Logger::Write(const std::string& message, const T& ...t)
{
if (s_CurrentLogLevel <= LogLevel::TRACE)
writeToStream(replacePlaceholders(message, std::vector<std::string>{ stringConvert(t)... }));
}
// Writes to the stream a message and inserts values into placeholders (should they exist) and finishes with the newline character with a default level of TRACE
template<typename ...T>
inline void Logger::WriteLine(const std::string& message, const T& ...t)
{
if (s_CurrentLogLevel <= LogLevel::TRACE)
writeToStream(replacePlaceholders(message, std::vector<std::string>{ stringConvert(t)... }) + "\n");
}
//
// Generic Methods: Write a level message (depending on the specified "LOG_LEVEL") to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), with "logLevel" importance
template<typename ...T>
inline void Logger::Write(LogLevel logLevel, const std::string& message, const T& ...t)
{
if (s_CurrentLogLevel <= logLevel)
writeToStream(replacePlaceholders(message, std::vector<std::string>{ stringConvert(t)... }));
}
// Writes to the stream a message and inserts values into placeholders (should they exist) and finishes with the newline character, with "logLevel" importance
template<typename ...T>
inline void Logger::WriteLine(LogLevel logLevel, const std::string& message, const T& ...t)
{
if (s_CurrentLogLevel <= logLevel)
writeToStream(replacePlaceholders(message, std::vector<std::string>{ stringConvert(t)... }) + "\n");
}
//
// Generic Methods: Write a TRACE level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of TRACE importance
template<typename ...T>
inline void Logger::Trace(const std::string& message, const T& ...t)
{
if (s_CurrentLogLevel <= LogLevel::TRACE)
writeToStream(replacePlaceholders(message, std::vector<std::string>{ stringConvert(t)... }));
}
//
// Generic Methods: Write a DEBUG level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of DEBUG importance
template<typename ...T>
inline void Logger::Debug(const std::string& message, const T& ...t)
{
if (s_CurrentLogLevel <= LogLevel::DEBUG)
writeToStream(replacePlaceholders(message, std::vector<std::string>{ stringConvert(t)... }));
}
//
// Generic Methods: Write a INFO level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of INFO importance
template<typename ...T>
inline void Logger::Info(const std::string& message, const T& ...t)
{
if (s_CurrentLogLevel <= LogLevel::INFO)
writeToStream(replacePlaceholders(message, std::vector<std::string>{ stringConvert(t)... }));
}
//
// Generic Methods: Write a WARN level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of WARN importance
template<typename ...T>
inline void Logger::Warn(const std::string& message, const T& ...t)
{
if (s_CurrentLogLevel <= LogLevel::WARN)
writeToStream(replacePlaceholders(message, std::vector<std::string>{ stringConvert(t)... }));
}
//
// Generic Methods: Write a ERROR level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of ERROR importance
template<typename ...T>
inline void Logger::Error(const std::string& message, const T& ...t)
{
if (s_CurrentLogLevel <= LogLevel::ERROR)
writeToStream(replacePlaceholders(message, std::vector<std::string>{ stringConvert(t)... }));
}
//
// Generic Methods: Write a CRITICAL level message to a stream
//
// Writes to the stream a message and inserts values into placeholders (should they exist), of CRITICAL importance
template<typename ...T>
inline void Logger::Critical(const std::string& message, const T& ...t)
{
if (s_CurrentLogLevel <= LogLevel::CRITICAL)
writeToStream(replacePlaceholders(message, std::vector<std::string>{ stringConvert(t)... }));
}
//
// StreamLogger class
//
// Used to log messages to a non-file stream (ex.: STDOUT, STDERR, STDLOG)
class StreamLogger : public Logger
{
protected:
//
// Protected members
//
StreamType m_StreamType;
//