xref: /haiku/src/apps/haikudepot/model/Logger.h (revision 106388ddbfdd00f4409c86bd3fe8d581bae532ec)
1 /*
2  * Copyright 2017-2022, 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 #define MILLIS_IN_DAY (1000 * 60 * 60 * 24)
18 
19 #define HDLOGLEVELCHAR(L) ( \
20 	L == LOG_LEVEL_INFO ? 'I' \
21 	: L == LOG_LEVEL_DEBUG ? 'D' \
22 	: L == LOG_LEVEL_TRACE ? 'T' \
23 	: L == LOG_LEVEL_ERROR ? 'E' \
24 	: '?')
25 
26 // These macros allow for standardized logging to be output.
27 // The use of macros in this way means that the use of the log is concise where
28 // it is used and also because the macro unwraps to a block contained with a
29 // condition statement, if the log level is not sufficient to trigger the log
30 // line then there is no computational cost to running over the log space.  This
31 // is because the arguments will not be evaluated.  Avoiding all of the
32 // conditional clauses in the code to prevent this otherwise would be
33 // cumbersome.
34 
35 #define HDLOGPREFIX(L) printf("@%08" B_PRId64 " {%c} <t:%" B_PRId32 "> ", \
36 	((system_time() / 1000) % MILLIS_IN_DAY), \
37 	HDLOGLEVELCHAR(L), \
38 	abs(find_thread(NULL) % 1000) \
39 );
40 
41 #define HDLOG(L, M...) do { if (Logger::IsLevelEnabled(L)) { \
42 	HDLOGPREFIX(L) \
43 	printf(M); \
44 	putchar('\n'); \
45 } } while (0)
46 
47 #define HDINFO(M...) HDLOG(LOG_LEVEL_INFO, M)
48 #define HDDEBUG(M...) HDLOG(LOG_LEVEL_DEBUG, M)
49 #define HDTRACE(M...) HDLOG(LOG_LEVEL_TRACE, M)
50 #define HDERROR(M...) HDLOG(LOG_LEVEL_ERROR, M)
51 
52 #define HDFATAL(M...) do { \
53 	printf("{!} (failed @ %s:%d) ", __FILE__, __LINE__); \
54 	printf(M); \
55 	putchar('\n'); \
56 	exit(EXIT_FAILURE); \
57 } while (0)
58 
59 typedef enum log_level {
60 	LOG_LEVEL_OFF		= 1,
61 	LOG_LEVEL_ERROR		= 2,
62 	LOG_LEVEL_INFO		= 3,
63 	LOG_LEVEL_DEBUG		= 4,
64 	LOG_LEVEL_TRACE		= 5
65 } log_level;
66 
67 
68 class Logger {
69 public:
70 	static	log_level			Level();
71 	static	void				SetLevel(log_level value);
72 	static	bool				SetLevelByName(const char *name);
73 
74 	static	const char*			NameForLevel(log_level value);
75 
76 	static	bool				IsLevelEnabled(log_level value);
77 	static	bool				IsInfoEnabled();
78 	static	bool				IsDebugEnabled();
79 	static	bool				IsTraceEnabled();
80 
81 private:
82 	static	log_level			fLevel;
83 };
84 
85 
86 #endif // LOGGER_H
87