Skip to content

Instantly share code, notes, and snippets.

@lucasdemarchi
Created February 16, 2018 18:44
Show Gist options
  • Select an option

  • Save lucasdemarchi/b87c1a681c04d06bc359f526bc64bca3 to your computer and use it in GitHub Desktop.

Select an option

Save lucasdemarchi/b87c1a681c04d06bc359f526bc64bca3 to your computer and use it in GitHub Desktop.
#include <stdarg.h>
#include <stdio.h>
#include <inttypes.h>
#define LOG_ERR "<1>"
#define LOG_WARN "<2>"
#define LOG_INFO "<3>"
#define LOG_DEBUG "<4>"
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define MULTICHAR_CONSTANT(a,b,c,d) ((int32_t)((a) | (b) << 8 | (c) << 16 | (d) << 24))
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
# define MULTICHAR_CONSTANT(d,c,b,a) ((int32_t)((a) | (b) << 8 | (c) << 16 | (d) << 24))
#elif __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__
# error A PDP? Seriously?
#endif
#define log_debug(...) _log(LOG_DEBUG __VA_ARGS__)
#define log_info(...) _log(LOG_INFO __VA_ARGS__)
#define log_warning(...) _log(LOG_WARN __VA_ARGS__)
#define log_error(...) _log(LOG_ERR __VA_ARGS__)
enum {
LOG_LEVEL_NONE = MULTICHAR_CONSTANT('<', '0', '>', 0),
LOG_LEVEL_ERR = MULTICHAR_CONSTANT('<', '1', '>', 0),
LOG_LEVEL_WARN = MULTICHAR_CONSTANT('<', '2', '>', 0),
LOG_LEVEL_INFO = MULTICHAR_CONSTANT('<', '3', '>', 0),
LOG_LEVEL_DEBUG = MULTICHAR_CONSTANT('<', '4', '>', 0),
};
int _log(const char *str, ...)
{
unsigned int level = *((uint32_t *)str);
/* ignore 4th char it may or may not be a NUL byte */
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
level &= 0xffffff;
#else
level >>= 8;
#endif
printf("%#x: %s\n", level, str + 3);
return 0;
}
int main()
{
log_error("this is a message");
log_warning("this is a message");
log_info("this is a message");
log_debug("this is a message");
log_debug("");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment