based on @inolasco answer, a static variable is not thread safe. a local variable is used instead.
void getFormattedTime(char * const p, int sz) { time_t rawtime; struct tm* timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); strftime(p, sz, "%Y-%m-%d %H:%M:%S", timeinfo); } int mylog(const char* fmt, ...) { // TODO: log to file also. // TODO: create a new log file daily va_list argptr; va_start(argptr, fmt); vfprintf(stderr, fmt, argptr);//log to stderr va_end(argptr); } #ifdef _WIN32 #define __SHORT_FILE__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__) #else #define __SHORT_FILE__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) #endif #define ___LOG___(fmt,level,path, ...) do{\ /* using local var and using a long name to avoid conflict*/ \ char LAgGV3nzJsTholGvGL2eTNXmhsqYe___xxooxxoo___[24];\ getFormattedTime(LAgGV3nzJsTholGvGL2eTNXmhsqYe___xxooxxoo___,\ sizeof(LAgGV3nzJsTholGvGL2eTNXmhsqYe___xxooxxoo___));\ mylog("%s [%s] [%s:%d] [%s] " fmt "\n", \ LAgGV3nzJsTholGvGL2eTNXmhsqYe___xxooxxoo___, \ level,\ path,\ __LINE__, \ __func__, \ ## __VA_ARGS__);\ }while(0) #define trace(fmt, ...) ___LOG___(fmt, "TRACE",__SHORT_FILE__, ## __VA_ARGS__) #define debug(fmt, ...) ___LOG___(fmt, "DEBUG",__SHORT_FILE__, ## __VA_ARGS__) #define info(fmt, ...) ___LOG___(fmt, "INFO",__SHORT_FILE__, ## __VA_ARGS__) #define warn(fmt, ...) ___LOG___(fmt, "WARN",__SHORT_FILE__, ## __VA_ARGS__) #define error(fmt, ...) ___LOG___(fmt, "ERROR",__SHORT_FILE__, ## __VA_ARGS__) #define tracel(fmt, ...) ___LOG___(fmt, "TRACE", __FILE__, ## __VA_ARGS__) #define debugl(fmt, ...) ___LOG___(fmt, "DEBUG", __FILE__, ## __VA_ARGS__) #define infol(fmt, ...) ___LOG___(fmt, "INFO", __FILE__, ## __VA_ARGS__) #define warnl(fmt, ...) ___LOG___(fmt, "WARN", __FILE__, ## __VA_ARGS__) #define errorl(fmt, ...) ___LOG___(fmt, "ERROR", __FILE__, ## __VA_ARGS__)
name them as follows:
info("%s", "a log"); infol("%s", "a log");
production:
2017-09-06 15:55:42 [INFO] [main.c:25] [main] a log 2017-09-06 15:58:08 [INFO] [d:\main.c:25] [main] a log