Created
December 28, 2021 19:49
-
-
Save mlabbe/d6797bfc6ead1019777ea7aad71a4204 to your computer and use it in GitHub Desktop.
Barebones code for a structured logger in C
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
#pragma once | |
// config | |
#define LOG_USE_STDIO 1 | |
#define LOG_USE_FILE 0 | |
#define LOG_USE_STRUCTURED 1 | |
#define LOG_LEVEL_TRACE 0 | |
#define LOG_LEVEL_WARN 1 | |
#define LOG_LEVEL_ERROR 2 | |
#if !defined(LOG_LEVEL) | |
# define LOG_LEVEL LOG_LEVEL_TRACE | |
#endif | |
// implementation | |
#define LOG__EOL "\x20\x1A\n" | |
#define LOG__EOM "\x1A\x1A\n" | |
#define LOG__FLAT(file, line, level, msg) \ | |
level " " file ":" line " |" msg "\n" | |
#define LOG__STRUCTURED(file, line, level, msg) \ | |
level LOG__EOL \ | |
"\tfile: " file LOG__EOL \ | |
"\tline: " line LOG__EOL \ | |
"\tmsg: " msg LOG__EOM "\n" | |
#if LOG_USE_STRUCTURED | |
# define LOG__LINE(file, line, level, msg) \ | |
LOG__STRUCTURED(file, line, level, msg) | |
#else | |
# define LOG__LINE(file, line, level, msg) \ | |
LOG__FLAT(file, line, level, msg) | |
#endif | |
#if LOG_USE_STDIO | |
# define LOG__STDIO_FPRINTF(stream, fmt, ...) \ | |
fprintf(stream, fmt, __VA_ARGS__); | |
#else | |
# define LOG__STDIO_FPRINTF(stream, fmt, ...) | |
#endif | |
#if LOG_USE_FILE | |
# define LOG__FILE(stream, fmt, ...) \ | |
fprintf(stream, fmt, __VA_ARGS__); \ | |
fflush(stream); | |
#else | |
# define LOG__FILE(stream, fmt, ...) | |
#endif | |
#define LOG__XSTR(x) #x | |
#define LOG__STR(x) LOG__XSTR(x) | |
#define LOG__DECL_LOGLEVELF(T, fmt, ...) \ | |
{ \ | |
LOG__STDIO_FPRINTF(stdout, \ | |
LOG__LINE(__FILE__, LOG__STR(__LINE__), #T, fmt), \ | |
__VA_ARGS__); \ | |
\ | |
LOG__FILE(handle, \ | |
LOG__LINE(__FILE__, LOG__STR(__LINE__), #T, fmt), \ | |
__VA_ARGS__); \ | |
} | |
#if LOG_LEVEL == LOG_LEVEL_TRACE | |
# define LOG_TRACEF(fmt, ...) LOG__DECL_LOGLEVELF("TRC", fmt, __VA_ARGS__); | |
#else | |
# define LOG_TRACEF(fmt, ...) | |
#endif | |
#if LOG_LEVEL <= LOG_LEVEL_WARN | |
# define LOG_WARNF(fmt, ...) LOG__DECL_LOGLEVELF("WRN", fmt, __VA_ARGS__); | |
#else | |
# define LOG_WARNF(fmt, ...) | |
#endif | |
#if LOG_LEVEL <= LOG_LEVEL_ERROR | |
# define LOG_ERRORF(fmt, ...) LOG__DECL_LOGLEVELF("ERR", fmt, __VA_ARGS__); | |
#else | |
# define LOG_ERRORF(fmt, ...) | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment