Skip to content

Instantly share code, notes, and snippets.

@25b3nk
Last active April 17, 2024 12:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 25b3nk/c2100acd3fb951b748d4244af9557ba6 to your computer and use it in GitHub Desktop.
Save 25b3nk/c2100acd3fb951b748d4244af9557ba6 to your computer and use it in GitHub Desktop.
C/C++ - printf() wrapper in macro
#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");
}
@25b3nk
Copy link
Author

25b3nk commented Aug 21, 2021

Compile the file & run:

g++ simple_log.cpp -o a.out
./a.out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment