1 /* 2 * Copyright 2017-2020, Andrew Lindesay <apl@lindesay.co.nz>. 3 * All rights reserved. Distributed under the terms of the MIT License. 4 */ 5 #ifndef LOGGER_H 6 #define LOGGER_H 7 8 #include <String.h> 9 #include <File.h> 10 #include <Path.h> 11 12 #include <ctype.h> 13 #include <stdio.h> 14 #include <stdlib.h> 15 16 17 // These macros allow for standardized logging to be output. 18 // The use of macros in this way means that the use of the log is concise where 19 // it is used and also because the macro unwraps to a block contained with a 20 // condition statement, if the log level is not sufficient to trigger the log 21 // line then there is no computational cost to running over the log space. This 22 // is because the arguments will not be evaluated. Avoiding all of the 23 // conditional clauses in the code to prevent this otherwise would be 24 // cumbersome. 25 26 #define HDLOGPREFIX(L) printf("{%c} ", toupper(Logger::NameForLevel(L)[0])); 27 28 #define HDLOG(L, M...) do { if (Logger::IsLevelEnabled(L)) { \ 29 HDLOGPREFIX(L) \ 30 printf(M); \ 31 putchar('\n'); \ 32 } } while (0) 33 34 #define HDINFO(M...) HDLOG(LOG_LEVEL_INFO, M) 35 #define HDDEBUG(M...) HDLOG(LOG_LEVEL_DEBUG, M) 36 #define HDTRACE(M...) HDLOG(LOG_LEVEL_TRACE, M) 37 #define HDERROR(M...) HDLOG(LOG_LEVEL_ERROR, M) 38 39 #define HDFATAL(M...) do { \ 40 printf("{!} (failed @ %s:%d) ", __FILE__, __LINE__); \ 41 printf(M); \ 42 putchar('\n'); \ 43 exit(EXIT_FAILURE); \ 44 } while (0) 45 46 typedef enum log_level { 47 LOG_LEVEL_OFF = 1, 48 LOG_LEVEL_ERROR = 2, 49 LOG_LEVEL_INFO = 3, 50 LOG_LEVEL_DEBUG = 4, 51 LOG_LEVEL_TRACE = 5 52 } log_level; 53 54 55 class Logger { 56 public: 57 static log_level Level(); 58 static void SetLevel(log_level value); 59 static bool SetLevelByName(const char *name); 60 61 static const char* NameForLevel(log_level value); 62 63 static bool IsLevelEnabled(log_level value); 64 static bool IsInfoEnabled(); 65 static bool IsDebugEnabled(); 66 static bool IsTraceEnabled(); 67 68 private: 69 static log_level fLevel; 70 }; 71 72 73 #endif // LOGGER_H 74