Last active
April 17, 2024 12:17
-
-
Save 25b3nk/c2100acd3fb951b748d4244af9557ba6 to your computer and use it in GitHub Desktop.
C/C++ - printf() wrapper in macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define GET_MACRO(_1,_2,NAME,...) NAME | |
/** | |
* @brief Info logs | |
* | |
*/ | |
// prints date, time, tag name, INFO in bold green color before actual message | |
#define LOGI2(tag, ...) printf("%s %s [%s]", __DATE__, __TIME__, tag); printf(" \033[1;32mINFO\033[0m "); printf(__VA_ARGS__); fflush(stdout); | |
// prints time, file name, line number, INFO in normal green color before actual message | |
#define LOGI1(...) printf("%s %s:%d", __TIME__, __FILE__, __LINE__); printf(" \033[0;32mINFO\033[0m "); printf(__VA_ARGS__); fflush(stdout); | |
// This chooses one of the two above functions based on arguments | |
#define LOGI(...) GET_MACRO(__VA_ARGS__, LOGI2, LOGI1)(__VA_ARGS__) | |
/** | |
* @brief Debug logs | |
* | |
*/ | |
// prints date, time, tag name, DEBUG in bold yellow color before actual message | |
#define LOGD2(tag, ...) printf("%s %s [%s]", __DATE__, __TIME__, tag); printf(" \033[1;33mDEBUG\033[0m "); printf(__VA_ARGS__); fflush(stdout); | |
// prints time, file name, line number, DEBUG in normal yellow color before actual message | |
#define LOGD1(...) printf("%s %s:%d", __TIME__, __FILE__, __LINE__); printf(" \033[0;33mDEBUG\033[0m "); printf(__VA_ARGS__); fflush(stdout); | |
// This chooses one of the two above functions based on arguments | |
#define LOGD(...) GET_MACRO(__VA_ARGS__, LOGD2, LOGD1)(__VA_ARGS__) | |
int main() { | |
LOGI("main", "This is an info log\n"); | |
LOGI("Hi\n\n"); | |
LOGD("main", "This is a debug log\n"); | |
LOGD("Hi\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile the file & run: