Skip to content

Instantly share code, notes, and snippets.

@cegme
Last active February 27, 2019 06:38
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 cegme/100ebbc62a8ae9996921f34a09d49dd8 to your computer and use it in GitHub Desktop.
Save cegme/100ebbc62a8ae9996921f34a09d49dd8 to your computer and use it in GitHub Desktop.
This Util header file creates macros that contain functions that help the logging and debugging process in C.
#ifndef UTIL_H
#define UTIL_H
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#define false 0
#define true 1
// This only works for C
static const char * currentTime () {
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
char * thetime = asctime(timeinfo);
thetime[strlen(thetime)-1] = '\0';
return (const char *) thetime;
}
// What is the current time
#define DATE_STRING currentTime()
#define clean_errno() (errno == 0 ? "None" : strerror(errno))
// Add code the only works if the debug flag is thrown
#ifdef DEBUG
#define debug(M, ...) fprintf(stderr, "DEBUG %s:%d: " M "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#else
#define debug(M, ...)
#endif
// If using clang, enable the -Wno-gnu-zero-variadic-macro-arguments
// for no errors
#define log_trace(M, ...) fprintf(stderr, "%s [trace] (%s:%d) | " M "\n", DATE_STRING, __FILE__, __LINE__, ##__VA_ARGS__)
#define log_debug(M, ...) fprintf(stderr, "%s [debug] (%s:%d) | " M "\n", DATE_STRING, __FILE__, __LINE__, ##__VA_ARGS__)
#define log_info(M, ...) fprintf(stderr, "%s [info] (%s:%d) | " M "\n", DATE_STRING, __FILE__, __LINE__, ##__VA_ARGS__)
#define log_err(M, ...) fprintf(stderr, "%s [error] (%s:%d: errno: %s) | " M "\n", DATE_STRING, __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)
#define log_warn(M, ...) fprintf(stderr, "%s [warn] (%s:%d: errno: %s) | " M "\n", DATE_STRING, __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)
#define check_mem(A) check((A), "Out of memory.")
#define log_timer(tic, toc, M, ...) fprintf(stderr, "%s [INFO] (%s:%d) | " M " (%lf msecs) \n", DATE_STRING, __FILE__, __LINE__, ##__VA_ARGS__, 1000.0*(toc-tic)/CLOCKS_PER_SEC)
#endif // UTIL_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment